Store the value of choices in db

Models.py
RATING_CHOICES = ((1, “Weak”), (2, “Average”), (3, “Good”), (4, “Excellent”))

class Question(models.Model):
    text = models.CharField(max_length=100)

class Teacher(models.Model):
    name = models.CharField(max_length=50)

class Answer(models.Model):
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    answer = models.IntegerField(choices=RATING_CHOICES, default=1)

Views.py

from .models import Question, RATING_CHOICES, Teacher, Answer

# Create your views here.

def index(request):

    question = Question.objects.all()

    a = Answer.objects.all()

    if request.method == 'POST':

        print(request.POST.get('teacher_selected'))

          # here I want to store the selected value from all the questions

    context = {'questions': Question.objects.all(),

                'rating_choices': RATING_CHOICES,

                'teacher': Teacher.objects.all()}

    return render(request, 'index.html', context)

index.html

<form action="{% url 'index'%}" method="POST">

    {% csrf_token %}

      <select name="teacher_selected">

        {% for teacher in teacher %}

          <option value="{{teacher}}">{{teacher}}</option>

          {% endfor %}

      </select>

    {% for question in questions %}

        <ol>{{ question.text }}</ol>

        

        {% for choice in rating_choices %}

          <input type="radio" name="question_{{question.id}}" value="{{choice.0}}">{{choice.1}}

        {% endfor %}

    {% endfor %} <br>

    <input type="submit" value="Vote">

</form>

I can get the value of dropdown list but I do not know how to do it with choices in each question.

This is best explained in the Forms docs. Start with the Working with forms page, particularly the section on the view regarding the handling of form data.

1 Like