User on main.html can choose category from select and get the question. App list all filtered questions by category. How to random questions and show the only one question?
I see, the all questions are qs
in ShowFilterView
, but how take questions
and randomize them?
views.py:
def is_valid_queryparam(param):
return param != '' and param is not None
def filter(request):
qs = Cards.objects.all()
categories = Category.objects.all()
category = request.GET.get('category')
if is_valid_queryparam(category):
qs = qs.filter(categories__name=category)
return qs
def MakeFilterView(request):
qs = filter(request)
context = {
'queryset': qs,
'categories': Category.objects.all()
}
return render(request, "cards/main.html", context)
def ShowFilterView(request):
qs = filter(request)
context = {
'queryset': qs,
'categories': Category.objects.all(),
}
return render(request, "cards/result.html", context)
models.py:
class Question(models.Model):
name = models.CharField('Вопрос', max_length=30)
def __str__(self):
return self.name
class Category(models.Model):
name = models.CharField('Категория', max_length=20)
def __str__(self):
return self.name
class Cards(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
categories = models.ManyToManyField(Category)
def __str__(self):
return str(self.question)
result.html:
{% extends 'base.html' %}
{% block content %}
{% for cards in queryset %}
{{ cards.question.name }}<br/>
{% endfor %}
{% endblock %}