Django在反向重定向中使用新创建的对象 [英] Django using a newly create object in reverse redirect

查看:152
本文介绍了Django在反向重定向中使用新创建的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从新创建的项目对象中提取id,以便我可以将用户重定向到包含新项目的页面。现在我得到'ProjectAddForm'对象没有属性'id'。

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


推荐答案

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.

instance = form.save()
return HttpResponseRedirect(reverse('project.views.detail', instance.id))

这篇关于Django在反向重定向中使用新创建的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆