0

I wanted to ask if there is a way to access instance id in ModelForm save method. (Need an object in order to add some extra data).

def save(self, *args, **kwargs):
    instance = super(MyForm, self).save(*args, **kwargs)
    print instance 
    return instance

And in all cases I am getting instance before it's saved in database (so it does not have an id and I can't attach objects to it)

xyres
  • 20,487
  • 3
  • 56
  • 85
Oleg Tarasenko
  • 9,324
  • 18
  • 73
  • 102

1 Answers1

1

It isn't necessary to override the ModelForm save() function. Instead, it's better to call save with commit=False. The Django docs explain this in depth, but here's a quick example:

new_object = form.save(commit=False)
new_object.name = 'Whatever'
new_object.save()

By calling save with commit=False, you get an object back. You can do whatever you want with this object, but make sure to save it once you make your changes!

allanlasser
  • 382
  • 2
  • 7
  • Well the thing is that I am not processing this form in my view. It's more like xadmin form, I have added for a specific model. So in general I can only tweak all form methods.. but can't access views – Oleg Tarasenko Jun 22 '15 at 16:34
  • Hm, well in that case sorry my answer wasn't helpful. Does the admin library you're using offer for class overrides and registrations, [as the Django admin does](http://stackoverflow.com/q/12321130/4256689)? – allanlasser Jun 23 '15 at 02:46