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

django, python

Solution

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

Problem

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

Original source

Related problems