Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelForm Instance vs Initial

I'm super new to Django, so bare with me. I'm trying to write a simple CRUD, using modelforms. In the update view, the form object initialization takes the arguments initial and instance, which confuses me. From django doc:

"As with regular forms, it’s possible to specify initial data for forms by specifying an initial parameter when instantiating the form. Initial values provided this way will override both initial values from the form field and values from an attached model instance."

Which confuses even more. I know my question isn't specific, but if someone could explain this and honestly, the background connection between the model and modelforms I would really appreciate it. Thanks y'all

like image 392
user1078378 Avatar asked Mar 20 '26 19:03

user1078378


1 Answers

Here is the example from Django docs;

from django.db import models
from django.forms import ModelForm

TITLE_CHOICES = [
    ('MR', 'Mr.'),
    ('MRS', 'Mrs.'),
    ('MS', 'Ms.'),
]

class Author(models.Model):
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=3, choices=TITLE_CHOICES)
    birth_date = models.DateField(blank=True, null=True)

    def __str__(self):
        return self.name


class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ['name', 'title', 'birth_date']

Your form -AuthorForm has information that name is string and it can't be greater than 100 characters. Because it's in your model -Author. Same for title and birth_date. title can't be greater than 3 characters and it must be one of the MR, MRS or MS.

You don't have to specify types, rules for form fields if you use model forms. Model forms can create forms quickly from your model and makes validations based on your model.

Let's assume you have an author instance which has name is Joe.

If you print author.name, it returns Joe.

form = AuthorForm(initial={'name': 'Patrick'}, instance=author)

If you print form['name'].value(), it returns Patrick, not Joe. It ignores author's name value. You overrided it in your form. It could be Joe if you didn't pass initial parameter.

like image 119
ysfkrcn Avatar answered Mar 22 '26 17:03

ysfkrcn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!