0

i need to make Quiz app on Django with random questions, model for Question is given below. I`ve already figured out how to randomize Questions in query set, but now i need to find a way to shuffle options of the question in template, but i cant figure it out by myself. Would be grateful for any advice

class Question(models.Model):
    question = models.CharField('Question text',max_length=250)
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    Option1 = models.CharField('answer 1',max_length=50)
    Option2 = models.CharField('answer 2',max_length=50)
    Option3 = models.CharField('answer 3',max_length=50)
    Option4 = models.CharField('answer 4',max_length=50)
    RightAnsw = models.IntegerField('Right answer nuber')
    mark = models.IntegerField('Points for right answer')

template.html

<form method="post">
    {% csrf_token %}
        {% for question in questions %}
            <p class="questiontext">Question {{ forloop.counter }}/{{ questions.count }}: {{ question.question }}</p>
            <p class="questionmark">Points:{{ question.mark }}</p>
            <p class="label">Choices:</p>
            <p class="option"><input type="radio" name="answer-{{ question.id }}" value="1">{{ question.Option1 }}</p>
            <p class="option"><input type="radio" name="answer-{{ question.id }}" value="2">{{ question.Option2 }}</p>
            <p class="option"><input type="radio" name="answer-{{ question.id }}" value="3">{{ question.Option3 }}</p>
            <p class="option"><input type="radio" name="answer-{{ question.id }}" value="4">{{ question.Option4 }}</p>
        {% endfor %}
        <button type="submit">End</button>
    </form>
  • Include the template and form code in the question. – Håken Lid Jun 02 '19 at 17:33
  • @HåkenLid done. – Vasyl Martyniv Jun 02 '19 at 17:35
  • 1
    This looks like wrong model (well NF1 normalization). You should make a separate model with `Choice` that links to the `Question`. – Willem Van Onsem Jun 02 '19 at 17:37
  • Possible duplicate of [django shuffle in templates](https://stackoverflow.com/questions/7162629/django-shuffle-in-templates) – Håken Lid Jun 02 '19 at 17:40
  • @WillemVanOnsem I`ve done that before, but changed it because i couldnt make inlines in admin panel. This way i can create a test and then in the same window add questions with answers for that test, as far as i tried i couldnt create tests, add to them questions and answers to questions in the same window. – Vasyl Martyniv Jun 02 '19 at 17:44

1 Answers1

0

Put them in a list

foo = [ques1, ques2, ques3, ques4]
list_x = random.sample(foo, len(foo))
Jay
  • 1,289
  • 3
  • 11
  • 22