为什么django中的url不读取主键而只是像字符串一样读取它?

发布于 2025-01-11 06:26:24 字数 675 浏览 0 评论 0原文

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)

调试时:它显示 当前路径 Leads/{{ Lead.pk }}/ 与其中任何一个都不匹配。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稚然 2025-01-18 06:26:24

{{}} 用于模板内部,而不是在 views.py 中使用

如果您的 urls.py 是用于例如

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

,那么您可以重定向为

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

{{}} 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)
写给空气的情书 2025-01-18 06:26:24

如果你想使用绝对和硬编码的url,这里不推荐:

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

而是使用reverse():

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


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

user8193706建议的url名称,Urls.py:

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

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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文