How to structure a quiz in django using ModelChoiceField?

90 views Asked by At

I am building an app using Django that will have a hard-coded quiz with 4 choices that users will fill out periodically. I am having trouble implementing this so that the user can fill out the form on one page and the instance is saved with relation to the user and current date. Could anybody help with how to go about this?

models.py

ANSWER_CHOICES = (
    (1, 'Never'),
    (2, 'Almost Never'),
    (3, 'Sometimes'),
    (4, 'Fairly Often'),
    (5, 'Very Often'),
)

class Answer(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='answer', null=True)
    answer = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.answer

class Quiz(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quiz', null=True)
    question = models.CharField(max_length=200)
    answer = models.ForeignKey(Answer, on_delete=models.CASCADE, related_name='quiz_answer', null=True)
    pub_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.question

views.py

def test(request):

    user = request.user

    questions = Quiz.objects.all()

    if request.method == 'POST':
        form = Form(request.POST)
        
        if form.is_valid():
            test = Quiz(
                answer=form.cleaned_data["answer"],
                user=user
            )
            test.save()
            return redirect('app:dashboard')
    else:
        form = Form()

    context = {
        'form':form,
    }
    
    return render(request, 'members/test.html', context)

forms.py

class Form(ModelForm):

    answer = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=(Answer.objects.all()))

    class Meta:
        model = Quiz
        fields = ['answer']

test.html

<form method="POST">
{% csrf_token %}
  <div class="card-body">
    {{ form|crispy }}
  </div>
  <!-- /.card-body -->
  <div class="card-footer">
   <button type="submit" class="btn btn-primary">Submit</button>
  </div>
</form>

Ideally, I would want the form to have this structure:

1.When did this happen?
a)recently
b)a while back
c) a long time ago
d)today

2.When was your last login?
a)recently
b)a while back
c) a long time ago
d)today
1

There are 1 answers

0
charanjeet singh On

Could you please elaborate your models.I am confused what you are trying to do what is the role of answer_choices. If you want user to select from that answer_choice varaible Then

field_name = models.CharField(max_length = 50,choices = answer_choice)

This will create a dropdown in frontend and you can even set a default value

Change in Views

def test(request):
   user = request.user
   questions = Quiz.objects.all()
   if request.method == 'POST':
       form = Form(request.POST)
       if form.is_valid():
          fm = form.save(commit = False)
          fm.user = request.user
          fm.save()
        return redirect('app:dashboard')


  context = {
    'form':form,
  }
return render(request, 'members/test.html', context)