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
?
models import User class InputUserInfo(forms. Form): phone = forms. CharField(max_length=20) instagram = forms. CharField(max_length=20) facebook = forms.
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 ).
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.
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.
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
Just use lv.pk
or lv.id
, after calling lv.save()
. The id is set on the instance after it's saved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With