@ok_wender

Как исправить ошибку NoReverseMatch?

Пытаюсь реализовать простейшее удаление элемента из БД при нажатии на ссылку. При данной реализации выскакивает ошибка Reverse for 'delete-city' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['delete\\-city/(?P[0-9]+)/$'].
Я новичок и только постигаю Django, перепробовал уже все, наверное. Понимаю, что ошибка глупая, буду благодарен любой помощи.

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 %}
  • Вопрос задан
  • 61 просмотр
Пригласить эксперта
Ответы на вопрос 1
SoreMix
@SoreMix
yellow
У объекта info нет поля id
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы