Model form save. Get the saved object
Asked Answered
T

4

42

If I have a model form and save it like:

f = FormModel(request.POST)
if f.is_valid():
    f.save()

How can I get back that object that has just been saved?

Tenstrike answered 15/9, 2011 at 8:53 Comment(0)
O
53

When you save a modelform, it returns the saved instance of the model. So all you have to do is assign it to a variable:

f = MyModelForm(request.POST)
if f.is_valid():
    m = f.save()

You do not need to mess around with commit=False or any of that stuff unless you are handling more complex data.

Obscene answered 15/9, 2011 at 14:45 Comment(1)
can you explain this concept in bit more depth ?Ampoule
O
30

If you know that the model is saved (so that a proper instance exists) you can also do:

model = form.instance
Ornstead answered 26/1, 2012 at 8:59 Comment(0)
T
8

Ah I just found this!

    # Create a form instance with POST data.
>>> f = AuthorForm(request.POST)

# Create, but don't save the new author instance.
>>> new_author = f.save(commit=False)

# Modify the author in some way.
>>> new_author.some_field = 'some_value'

# Save the new instance.
>>> new_author.save()

# Now, save the many-to-many data for the form.
>>> f.save_m2m()
Tenstrike answered 15/9, 2011 at 8:59 Comment(0)
C
0

@Fabian, that's for editing an instance that wasn't previously included in your model form,

E.g your model form covers name, age, gender but in your model there is another field maybe country and you want to add it by yourself not your user, so you reveal the required fields and then you use the above procedure to add the rest This worked for me on the above prob

If form.is_valid()
    Current_form=form.save()
    My_new_id=Curret_form.id

This printed the id of the newly created objected which I later saved in another model

Campanulate answered 3/6, 2020 at 15:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.