urls
from django.urls import path from . import views from django.conf.urls import url urlpatterns = [ path( '', views.TestingView.as_view(), name='test'), #path( '<int:pk>', views.TestingDetailView.as_view(), name='test-detail'), url(r'^(?P<pk>\d+)$', views.TestingDetailView.as_view(), name='test-detail'), url(r'^answer/(?P<pk>\d+)$', views.TestingDetailView.as_view(), name='answer'),
models
rom django.db import models # Create your models here. class Testing(models.Model): test_name = models.CharField('Название теста', max_length=254) def __str__(self): return self.test_name class Meta: verbose_name = "Тест" verbose_name_plural = "Тесты" class Questions(models.Model): question = models.CharField('Вопрос', max_length=254) id_testing = models.ForeignKey(Testing, on_delete=models.CASCADE, verbose_name='Тест', blank=True, null=True, related_name='quest_testing' ) def __str__(self): return self.question class Meta: verbose_name = "Вопрос" verbose_name_plural = "Вопросы" class Answer(models.Model): text_questions = models.TextField('Текст ответа') id_questions = models.ForeignKey(Questions, on_delete=models.CASCADE, verbose_name='Вопрос', blank=True, null=True, related_name='answer_quest') correct_answer = models.BooleanField(default=False) def __str__(self): return self.text_questions class Meta: verbose_name = "Ответ" verbose_name_plural = "Ответы"
views
from django.template.context_processors import csrf from django.shortcuts import render, redirect # Create your views here. # получение данных из бд from django.views import generic from django.views.generic.base import View from django.views.generic import DetailView from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import Testing, Questions, Answer #Список тестов class TestingView(View): def get(self, request): test = Testing.objects.all() return render(request, "testing/index.html", {"tests": test}) #Вопросы и ответы class TestingDetailView(DetailView, View): model = Testing template_name = 'testing/detail_view.html' context_object_name = 'testing'
<h2>{{ testing.test_name }}</h2> {% for answer in testing.quest_testing.all %}<br><br> <b>{{ answer.question }}</b> / {{ answer.id }} <br> {% for answers in answer.answer_quest.all %} <form method="POST"> {% csrf_token %} <input type="radio" id="id_{{ answers.id }}" type="radio" value="{{ answers.correct_answer }}" name="radio_{{ answer.id }}" /> {{ answers.text_questions }} <b>({{ answers.correct_answer }} / {{ answers.id }})</b><br> {% endfor %} {% endfor %} <br><br><button type="submit" class="btn badge-primary"> Ответить </button> </form> {% endblock %}