Django 在反向重定向中使用新创建的对象
我试图从新创建的项目对象中提取 id,以便我可以将用户重定向到包含新项目的页面。现在我得到“'ProjectAddForm'对象没有属性'id'”。
我在网上读到这应该可行,但由于某种原因却行不通。
if request.method == 'POST':
form = ProjectAddForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('project.views.detail', args=(form.id)))
表格.py
class ProjectAddForm(forms.ModelForm):
class Meta:
model = Project
I am trying to pull the id from the newly created project object so I can redirect the user to the page containing the new project. Right now I get "'ProjectAddForm' object has no attribute 'id'".
I have read online that this should work but for some reason it's not.
if request.method == 'POST':
form = ProjectAddForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('project.views.detail', args=(form.id)))
Forms.py
class ProjectAddForm(forms.ModelForm):
class Meta:
model = Project
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
save
方法返回您的模型对象。获取对它的引用,然后您将获得反向重定向所需的“id”。The
save
method returns your model object. Grab a reference to it and then you will have the 'id' you need for your reverse redirect.