开发者

Django using a newly create object in reverse redirect

开发者 https://www.devze.com 2023-01-18 13:41 出处:网络
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 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()
            ret开发者_运维百科urn HttpResponseRedirect(reverse('project.views.detail', args=(form.id)))

Forms.py

class ProjectAddForm(forms.ModelForm):

    class Meta:
        model = Project


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

精彩评论

暂无评论...
验证码 换一张
取 消