Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Django can automatically populate a form by setting default values for each field or by using data pre-populated from the database.

  1. Setting Default Values:

In your forms.py, you can set default values for each field. For example, let's say you have a model called Student that has fields 'name', 'email', and 'year'. Your form could automatically set defaults like this:

class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = ['name', 'email', 'year']

    def __init__(self, *args, **kwargs):
        super(StudentForm, self).__init__(*args, **kwargs)
        self.fields['name'].initial = 'John Doe'
        self.fields['year'].initial = 'Freshman'
  1. Pre-Populating Form Data:

You can also prepopulate form data from a database by using the initial parameter of the form. Let's say you have a model called Student and you want to prepopulate the form with a specific student's information. Your view could look something like this:

from django.shortcuts import render
from myapp.models import Student
from myapp.forms import StudentForm

def edit_student(request, id):
    student = Student.objects.get(id=id)
    form = StudentForm(initial={
                'name': student.name,
                'email': student.email,
                'year': student.year
            })

    context = {'form': form}
    return render(request, 'edit_student.html', context)

This would prepopulate the form with the data of the Student object with id = id.