I am making a simple todo list application but while adding a delete button, I am receiving the error. I tried many things searching on internet but couldn't solve the issue, probably because i am new to django.So, your help will be very important.
urls.py(of app):
from django.conf.urls import url
from django.urls import path
from . import views
urlpatterns=[
path('',views.home,name='home'),
url('delete/<str:id>', views.delete_data,name='deldata'),
]
views.py:
from django.shortcuts import get_object_or_404, render,redirect
from todo.models import value
from django.http import HttpResponseRedirect
# Create your views here.
from .forms import TitleForm
from django.urls import reverse
def home(request):
values=value.objects.all()
form=TitleForm
if request.method=='POST':
form=TitleForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form=TitleForm()
return render(request,'home.html',{'values':values,'form':form})
#delete
def delete_data(request, id ):
ggwp=value.objects.get(id=id)
if request.method=="POST":
ggwp=value.objects.get(id=id)
ggwp.delete()
return HttpResponseRedirect(reverse('deldata', kwargs={'id':id}))
context={'ggwp':ggwp}
return render(request,'/',context)
models.py:
from django.db import models
# Create your models here.
class value(models.Model):
task=models.CharField(max_length=200)
complete=models.BooleanField(default=False)
created=models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.task
home.html(One and only html page):
<h3>TO DO LIST</h3>
<form method="POST" action="\">
{% csrf_token %}
{{form.task}} <input type='submit' name='add' value="add" >
</form>
{% for val in values %}
{{val}}
<form action="{% url 'deldata' val.id %}" method="POST" class="in-line">
{% csrf_token %}
<input type="submit" value="Delete" >
</form>
{% endfor %}
traceback:
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'deldata' with arguments '(15,)' not
found. 1 pattern(s) tried: ['delete/<str:id>']
[05/Oct/2021 22:37:17] "GET / HTTP/1.1" 500 127858
Its my first question, so sorry if I have made any mistakes while writing the question.
CodePudding user response:
You are using *path(…)
[Django-doc] syntax with the url(…)
function [Django-doc]. You should work with a path(…)
here:
urlpatterns=[
path('',views.home,name='home'),
# ↓ path, not url
path('delete/<str:id>/', views.delete_data,name='deldata'),
]
Normally paths also end with a slash, altough that is not required, it is common.
Note: As of django-3.1,
url(…)
[Django-doc] is deprecated in favor ofre_path(…)
[Django-doc]. Furthermore a new syntax for paths has been introduced with path converters: you usepath(…)
[Django-doc] for that.