48

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.

vishes_shell
  • 22,409
  • 6
  • 71
  • 81
EsseTi
  • 4,079
  • 5
  • 36
  • 63

2 Answers2

67

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,))
Bart
  • 9,925
  • 7
  • 47
  • 64
mpaolini
  • 1,334
  • 10
  • 7
  • 6
    yup it works `def get_success_url(self): return reverse('offerta_create',args=(self.object.id,))` – EsseTi Nov 09 '12 at 15:03
  • @EsseTi When I try to use `self.object.id` the way that you did, I get `None` back, even though `self.object` definitely exists and it's getting saved to my database (MySQL). Any insights into why that would be? – ZAD-Man Aug 08 '14 at 22:05
  • 1
    not really. may be that it's not (yet) saved so there's no id. what happens if u try to access another field? – EsseTi Aug 11 '14 at 08:49
  • 1
    @EsseTi Whoops, didn't see this until now (I have the same issue again :P). Using any other field works fine. `self.object` gives me an object just fine, with all the other data properly there, but `id` is `None`. – ZAD-Man Sep 08 '14 at 19:45
  • is the object in the db?if so id should be there. if not it means that it's not stored, so no id (this is just a guess) – EsseTi Sep 09 '14 at 08:23
0

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.

Community
  • 1
  • 1
Chirael
  • 3,025
  • 4
  • 28
  • 28
  • Daniel's answer does not address this, the problem in that question was poor table design and not letting Django deal with the autoincrement of the primary key. – diek Feb 14 '19 at 19:22