Populate fields that aren't in a Django ModelForm

I ran across an issue today that, in hindsight, was simple and probably a result of not reading the Django documentation thoroughly enough. I'm definitely still in the "learning" phase of my relationship with Django.

Consider this (imperfect) example: you're using a ModelForm to allow users of your web app to create a Student. The user would supply the student's name, date of birth, and address in a form, but the student ID should be generated based on their other information (e.g. name and date of birth).

The ModelForm object won't give you access to the underlying Model's student_id field unless you include it with the form, which is undesirable. You could also save the Student to the database, then update its student_id field, but that's pretty inefficient. The better solution:

# Model
class Student(models.Model):
    student_id = models.CharField()
    name = models.CharField()
    dob = models.DateField()
    address = models.CharField()

# ModelForm
class AddStudentForm(forms.ModelForm):
    class Meta:
        model = Student
        # don't include student_id
        fields = ['name', 'birthday', 'address']

# View
def add_student(request):
    if form.is_valid():
        # this will gave you an instance of the Student model without saving it to the db
        student = form.save(commit=False)
        # then you can create the student_id and save to the db
        student.student_id = create_id(student.name, student.dob)
Show Comments