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

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.



Solution 1:[1]

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')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1