Home > Enterprise >  How to create single Form for two models that are related by a Foreign Key?
How to create single Form for two models that are related by a Foreign Key?

Time:08-06

I developed a voting system using Python and Django. I would like the user to be able to register new polls. However, when the user registers a new poll, it results in an IntegrityError. It looks like it can't get the ID of the first model. How do I fix this error? The photo of the error and the form is below...

models.py

from django.db import models
from django.utils import timezone


class Question(models.Model):
     question_text = models.CharField(max_length=200)
     pub_date = models.DateTimeField(default=timezone.now, verbose_name='Date')
     show = models.BooleanField(default=True)

    def __str__(self):
        return self.question_text

class Choice(models.Model):
     question = models.ForeignKey(Question, on_delete=models.CASCADE)
     choice_text = models.CharField(max_length=200)
     votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

forms.py

 from django.forms import ModelForm

 from .models import *


 class addPollsForm(ModelForm):
     class Meta:
         model = Question
         fields = ['question_text', 'pub_date', ]

 class addChoiceForm(ModelForm):
     class Meta:
         model = Choice
         fields = ['choice_text']

views.py

def addPollsPage(request):

    if request.user.is_authenticated:
        formAddPolls = addPollsForm()
        formAddChoice = addChoiceForm()
    
        if request.method == 'POST':
            formAddPolls = addPollsForm(request.POST)
            formAddChoice = addChoiceForm(request.POST)
        
            if formAddPolls.is_valid():
                formAddPolls.save()
            if formAddChoice.is_valid():
                formAddChoice.save() 
        
            return redirect('votacao:index')

        context = {'formAddPolls': formAddPolls,
                   'formAddChoice': formAddChoice,
                  }
        return render (request, 'votacao/addPolls.html', context)

    else:
        return redirect('main')

addPolls.html

    <form action="" method="POST">
            {% csrf_token %}
            {{formAddPolls.as_p}}
            {{formAddChoice.as_p}}
            {{formAddChoice.as_p}}
            {{formAddChoice.as_p}}
            <br>
       <input type="submit" name="Submit">
    </form>

IntegrityError error photo

CodePudding user response:

The problem here is that the addChoiceForm dosn't have a question assigned. So, you need to add this manually.

if formAddPolls.is_valid():
    question = formAddPolls.save()
    if formAddChoice.is_valid():
        formAddChoice.question=question
        formAddChoice.save()

You can see also inlineformset_factory. Check this in the docs and here is an example.

  • Related