Django using a newly create object in reverse redirect

怎甘沉沦 提交于 2019-12-11 03:05:14

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/3859474/django-using-a-newly-create-object-in-reverse-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!