为什么django中的url不读取主键而只是像字符串一样读取它?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
{{}}
用于模板内部,而不是在views.py
中使用如果您的
urls.py
是用于例如,那么您可以重定向为
{{}}
is used inside templates not inviews.py
If your
urls.py
is for e.g.Then you can redirect as
如果你想使用绝对和硬编码的url,这里不推荐:
而是使用reverse():
user8193706建议的url名称,Urls.py:
If you want to use an absolute and hard-coded url which is not recommended here:
But instead use reverse():
Name of url as suggested by user8193706, Urls.py: