brambo lamo
brambo lamo

Reputation: 33

Django - delete button is not redirecting to the correct path

I am following a tutorial to make a to-do list website. Upon trying to implement a delete button, I am encountering this error.

Page not found (404) Request Method: GET Request URL: http://localhost:8000/%7B%25%20url%20'delete'%20things.id%20%25 Using the URLconf defined in todo.urls, Django tried these URL patterns, in this order: admin/ [name='home'] delete/"" [name='delete'] The current path, {% url 'delete' things.id %, didn't match any of these.

Relevant code: views.py

from django.shortcuts import render, redirect
from .models import List
from .forms import ListForm
from django.contrib import messages
# Create your views here.
def home(request):
    if request.method == 'POST':
        form = ListForm(request.POST or None)

        if form.is_valid():
            form.save()
            all_items = List.objects.all
            messages.success(request, ('Item Has Been Added To List!'))
            return render(request, 'home.html', {'all_items': all_items})

    else:
        all_items = List.objects.all
        return render(request, 'home.html', {'all_items': all_items})

def delete(request, list_id):
    item = List.objects.get(pk=list_id)
    item.delete()
    messages.success(request, ('Item Has Been Deleted!'))
    return redirect('home')

home.html

<tr>
            <td>{{ things.item }}</td>
            <td><center>{{ things.completed }}</center></td>
            <td><center><a href = "{% url 'delete' things.id %}"> Delete</a></center></td>
</tr> 

urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('', views.home, name="home"),
    path('delete/<list_id>', views.delete, name="delete"),
]

Upvotes: 3

Views: 1679

Answers (2)

Matt Cremeens
Matt Cremeens

Reputation: 5151

You need a regular expression to say a number is coming

path('delete/(?P<list_id>)[\d]+)/$', views.delete, name="delete"),

Upvotes: 1

Pedram
Pedram

Reputation: 3920

urls.py:

from django.urls import path
from . import views
urlpatterns = [
    path('', views.home, name="home"),
    path('delete/<int:list_id>/', views.delete, name="delete"),
]

You need to specify the int type in the url.

And also the trailing /

Upvotes: 2

Related Questions