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)

1
  • It's a bit strange. When I do print kwargs it says {'commit': False}. interesting why Commented Jun 22, 2015 at 16:48

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.