Importing models to forms in Django

Viewed 63

I am making a quiz web application and I want to create answers to questions from admin panel, not writing a code for each set of answers. How can I do that?

forms:

from django import forms

ANSWER_CHOICES = [
    ('1', 'First'),
    ('2', 'Second'),
    ('3', 'Third'),
]
class AnswerForm(forms.Form):
    answer = forms.ChoiceField(
        label = '',
        required=False,
        widget=forms.RadioSelect,
        choices=ANSWER_CHOICES,
    )

models:

from django.db import models

class Questions(models.Model):
    title = models.CharField('Question', max_length=200)

    def __str__(self):
        return self.title
1 Answers

In your models.py:

class Question(models.Model):
    
    OPTION_CHOICES = [
        ('option1', 'option1'),
        ('option2', 'option2'),
        ('option3', 'option3'),
        ('option4', 'option4'),
    ]
    
    question = models.TextField(unique=True)
    option1 = models.CharField(max_length=200,help_text='Required')
    option2 = models.CharField(max_length=201,help_text='Required')
    option3 = models.CharField(max_length=202,null=True,blank=True,help_text='(Optional)')
    option4 = models.CharField(max_length=204,null=True,blank=True,help_text='(Optional)')
    answer = models.CharField(choices=OPTION_CHOICES,max_length=205,help_text='This answer must be match for given above option..')
    answer_hidden = models.CharField(max_length=206,null=True,blank=True,verbose_name='True Answer',help_text="Your selected option's answer",default='No select any ans. yet!!')
    point = models.IntegerField(default = 1,help_text='Student How many points will get for this given question?')
    solution = models.TextField(blank=True,null=True,help_text='(Optional) If possible! give the specific solution for this question..')
    cr_date = models.DateTimeField(auto_now=True,verbose_name='Created Date')
    
    class Meta:
        verbose_name_plural = "Questions"
        
    def save(self, *args, **kwargs):
        super(Question, self).save(*args, **kwargs)
        if self.answer == 'option1':
            self.answer_hidden = self.option1
            super(Question, self).save(*args, **kwargs)
        elif self.answer == 'option2':
            self.answer_hidden = self.option2
            super(Question, self).save(*args, **kwargs)
        elif self.answer == 'option3':
            self.answer_hidden = self.option3
            super(Question, self).save(*args, **kwargs)
        elif self.ans2wer == 'option4':
            self.answer_hidden = self.option4
            super(Question, self).save(*args, **kwargs)
                        
    def __str__(self):
        return str(self.question)

select option from the admin panel -> this selected option's ans. automatic save in hidden_answer field -> show this ans. in front-end

I already made this app Quiz_app

Related