8👍
✅
save() should return the newly created instance.
if contractor_form.is_valid():
instance = contractor_form.save()
parameters['contractor'] = instance
where id would be instance.id
, or even better instance.pk
.
Regardless of whether you define a
primary key field yourself, or let
Django supply one for you, each model
will have a property called pk. It
behaves like a normal attribute on the
model, but is actually an alias for
whichever attribute is the primary key
field for the model. You can read and
set this value, just as you would for
any other attribute, and it will
update the correct field in the model.
Follow-up on comment:
Well it does work by default, so there must be something else wrong.
models.py
class Category(models.Model):
name = models.CharField(max_length=70)
slug = models.SlugField()
forms.py
from django import forms
from models import Category
class MyModelForm(forms.ModelForm):
class Meta:
model = Category
Test in shell:
In [3]: from katalog.forms import MyModelForm
In [4]: data = {'name':'Test', 'slug':'test'}
In [5]: form = MyModelForm(data)
In [6]: instance = form.save()
In [7]: instance
Out[7]: <Category: Test>
In [8]: instance.id
Out[8]: 5L
Source:stackexchange.com