Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the model ID from a Django form after having saved it

Tags:

python

django

view.py

someForm = SomeForm(request.POST)
...
someForm.customSave(request.user)

forms.py

class SomeForm(ModelForm):

    class Meta:
        model = Some

    def customSave(self,user):
        lv = self.save(commit=False)
        lv.created_by = user
        lv.save()

How can I get the id of the model (or the model) I have just saved from someForm?

like image 374
Robert Johnstone Avatar asked Apr 13 '12 16:04

Robert Johnstone


People also ask

How do I link models and forms in Django?

models import User class InputUserInfo(forms. Form): phone = forms. CharField(max_length=20) instagram = forms. CharField(max_length=20) facebook = forms.

What does form Save Do Django?

form. save() purpose is to save related model to database, you are right. You're also right about set_password , for more info just read the docs. Django knows about model and all it's data, due to instance it's holding (in your case user ).

What is form Is_valid () in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

Do Django models have ID?

Does Django model have ID? Primary Keys By default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field.


2 Answers

Since the behavior of ModelForm.save is to return the instance, you might want to return the instance in your customSave method

def customSave(self, user):
    lv = self.save(commit=False)
    lv.created_by = user
    lv.save()
    return lv

then you can access the pk or id on the instance

inst = someForm.customSave(request.user)
inst.pk or inst.id
like image 74
Jason Keene Avatar answered Oct 01 '22 16:10

Jason Keene


Just use lv.pk or lv.id, after calling lv.save(). The id is set on the instance after it's saved.

like image 44
Chris Pratt Avatar answered Oct 01 '22 17:10

Chris Pratt