How to save a field after commit=False with model Form in Django?
django, forms, model, python
Solution
A `ModelForm` will by default include and validate all fields of the model. If you always assign the `alias` value yourself in the view, then you don't need the `alias` field in the form and you can just exclude it:
class BookForm(ModelForm):
class Meta:
model = Book
fields = ('name', 'description')
# NOTE: you can also use excludes, but many consider it a bad practice
As always, Django docs can tell you more about it.
Problem
I have a model: ``` class Book(models.Model): name = models.CharField(max_length=100) alias = models.CharField(max_length=100) description = models.TextField() def __unicode__(self): return self.name ``` and a ModelForm in forms.py: ``` class BookForm(ModelForm): class Meta: model = Book ``` So I'm trying to make something like this in my views: ``` def register_book(request): if request.method == 'POST': formul = BookForm(request.POST) if formul.is_valid(): new_book=formul.save(commit=False) new_book.alias='foo' new_book.save() return HttpResponseRedirect('/') ``` So, I'm saving from a html "form" the name & description, but the alias I need to save after I get the form. But isn't working.