samedi 29 août 2020

Django Foreign key on Modelform

I'm working on the project that Django tutorial provides. I'm just trying to expand functionality like: login, registration, poll CRUD and so on. I have two models:

class Question(models.Model):
    question_text = models.CharField(max_length=70)
    describtion = models.TextField(null=True, max_length=200)
    pub_date = models.DateTimeField(auto_now=True)

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

    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

Thet connected via foreignkey. So, each choice has it's own question. And set up in admin dashboard,so if i try to create new question i can add as many choices i want. I just configured it in admin.py. Problem is this I want to have a form that user can submit a question and its choices. I've done first part that user can create poll question, but cannot handle to add choices while creating question itself. Choices should automatically connected to Question. Please help me solve this problem. My ModelForm looks like this


class QuestionForm(ModelForm):
    class Meta:
        model = Question
        fields = ['question_text','describtion']
        widgets = {
            'question_text': forms.TextInput(attrs={'class':'form-control','placeholder':'Enter name for poll','id':'title'}),
            'describtion': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter name for poll','id':'describtion'})
        }



Aucun commentaire:

Enregistrer un commentaire