django createview how to get the object that is created

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 12:47:10

问题


i've two concatenated form. Basically user fills in the first form and then is redirected to the second one which adds value to the data of the first form. E.G. I've a form Movie (first form) and then i'm redirected to the form (actor) which add the actor to the movie.

in my case the Movie = Chiamata and Actor = Offerta (i keep the italians name for what i need :D)

fine.

those are my urls in the urls.py

url(r'^chiamata/$', ChiamataCreate.as_view(),name='chiamata_create'),
url(r'^chimamata/(?P<pk>\d+)/offerta$', OffertaCreate.as_view(), name='offerta_create'),

i've this create view

class ChiamataCreate(CreateView):
    template_name = 'chiamata_form.html'
    form_class = ChiamataForm
    success_url=reverse_lazy('offerta_create',args=(??,))

now the problem is how i can get the PK of the object created by the chiamataForm. I need that to add it to the the url of offerta_create.


回答1:


maybe you could use get_success_url() method (see reference)

In this case, it'd be something like:

def get_success_url(self):
    return reverse('offerta_create',args=(self.object.id,))



回答2:


Please see the accepted answer on Why doesn't self.object in a CreateView have an id after saving to the database? - once I removed the "id" fields from my models, and let Django default to its own id AutoField on each model as recommended in that answer, self.object.id worked fine in my CreateView.



来源:https://stackoverflow.com/questions/13309479/django-createview-how-to-get-the-object-that-is-created

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