O
O
ok_wender2021-04-11 11:56:31
Django
ok_wender, 2021-04-11 11:56:31

How to fix NoReverseMatch error?

I'm trying to implement the simplest deletion of an element from the database when clicking on a link. This implementation throws an error Reverse for 'delete-city' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['delete\\-city/(?P[0-9]+)/$'].
I'm new and just learning Django, I've tried everything, I guess. I understand that the mistake is stupid, I will be grateful for any help.

URLs.py:

from django.urls import path
from . import views


urlpatterns = [
    path('', views.index),
    path('delete-city/<int:id>/', views.delete_city, name="delete-city"),
]


views.py:

import requests
from django.shortcuts import render, redirect
from .models import City
from .forms import CityForm
from django.http import HttpResponseRedirect
from django.http import HttpResponseNotFound
from django.urls import reverse


def index(request):
    key = '9adaa09047557e91e33f881d8de28019'
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=' + key

    if(request.method == 'POST'):
        form = CityForm(request.POST)
        form.save()

    form = CityForm()

    cities = City.objects.all()

    all_cities = []

    for city in cities:
        res = requests.get(url.format(city.name)).json()
        if res.get('main'):
            city_info = {
                'city': city.name,
                'temp': res["main"]["temp"],
                'icon': res["weather"][0]["icon"],
                'error': False,
            }
        else:
            city_info = {
                'city': city.name,
                'error': True,
            }

        all_cities.append(city_info)

    context = {'all_info': all_cities, 'form': form}

    return render(request, 'weather/index.html', context)


def delete_city(request, id):
    city_card = City.objects.get(id=id)
    city_card.delete()
    return redirect('index')


models.py:

from django.db import models


class City(models.Model):

    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name


index.html:

{% for info in all_info %}
      <form action="" method="post">
        {%csrf_token%}

        <div class="result">
          Город : {{ info.city }} <a class="del_city" href="{% url 'delete-city' id=info.id %}">Удалить</a> <br>
          <div class="rez">
            Температура в {{ info.city }} : {{ info.temp }} <sup>°</sup> <br>
            <div class="img_temp"><img height="70px" width="70px" src="https://openweathermap.org/img/w/{{info.icon}}.png" alt="weather_photo" class=""></div>
          </div>

        </div>
      </form>
{% endfor %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-04-11
@soremix

Info object has no id field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question