Handling Django Multiple Form

I have problem when dealing with django form. I have 3 different forms and I render those form in the same page. Anyway my problem has different case with formset, so I will not use this method.

Here is my models and forms.

# models.py
class Student(models.Model):
    name = models.CharField(max_length=120)
    
    def __unicode__(self):
        return self.name

class Document(models.Model):
    student = models.ForeignKey(Student)
    name = models.CharField(max_length=120)
    
    def __unicode__(self):
        return self.name

class Score(models.Model):
    student = models.ForeignKey(Student)
    name = models.CharField(max_length=120)
    
    def __unicode__(self):
        return self.name


# forms.py
class StudentForm(ModelForm):
    class Meta:
        model = Student

class DocumentForm(ModelForm):
    class Meta:
        model = Student

class ScoreForm(ModelForm):
    class Meta:
        model = Score

And here is my post handler for three form above. When I submit the form, some of the data missing from post request.

def student_registration(request, uuid=None):

    student_form = StudentForm(request.POST or None)
    document_form = DocumentForm(request.POST or None)
    score_form = ScoreForm(request.POST or None)

    if student_form.is_valid() and document_form.is_valid() and score_form.is_valid():
        student = student_form.save()

        doc = document_form.save(commit=False)
        doc.student = student
        doc.save()

        score = score_form.save(commit=False)
        score.student = student
        score.save()

        return redirect('student')

I just realized my models has name field and by default django form will generate id=”id_field_name” as the html id field selector. And the problem fixed after I add prefix in my form instantiation.

student_form = StudentForm(request.POST or None, prefix='student')
document_form = DocumentForm(request.POST or None, prefix='document')
score_form = ScoreForm(request.POST or None, prefix='score')

Don’t forget the prefix must be unique, then django form will generate “id_yourprefix_yourfield” as the html id.

Reference: https://docs.djangoproject.com/en/dev/ref/forms/api/#prefixes-for-forms

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s