Home > database >  why is the url in django not reading the primary key and just reading it like a string?
why is the url in django not reading the primary key and just reading it like a string?

Time:03-03

def lead_update(request,pk) :
lead = Lead.objects.get(id=pk)
form = LeadForm()
if request.method == "POST" :
    form = LeadForm(request.POST)
    if form.is_valid() :
        first_name = form.cleaned_data['first_name']
        last_name = form.cleaned_data['last_name']
        age = form.cleaned_data['age']
        lead.first_name = first_name
        lead.last_name = last_name
        lead.age = age
        lead.save()
        return redirect("/leads/{{ lead.pk }}/") # the problem

context = {
    "form" : form,
    "lead" : lead
}
return render(request,"leads/lead_update.html",context)

on debug : it is showing The current path, leads/{{ lead.pk }}/, didn't match any of these.

CodePudding user response:

{{}} is used inside templates not in views.py

If your urls.py is for e.g.

path('lead/<pk>/', views.lead_update, name='lead_update')

Then you can redirect as

return redirect('lead_update', pk=lead.pk)

CodePudding user response:

If you want to use an absolute and hard-coded url which is not recommended here:

return redirect(f"/leads/{ lead.pk }/") # only single curly brackets

But instead use reverse():

from django.http import HttpResponseRedirect
from django.urls import reverse


return HttpResponseRedirect(reverse('lead-update', args=[lead.pk]))

Name of url as suggested by user8193706, Urls.py:

path('lead/<pk>/', views.lead_update', name='lead_update')
  • Related