All Quiz
{% comment %} English {% endcomment %}
{% for category in categories %}
{{category.name}}
{% endfor %}
{% comment %}
Search
{% endcomment %}
Search
{% if quizzes|length > 0 %} {% comment %} {{ quizzes|length }}, here quizzes object all properties will be counted {% endcomment %}
{% for quiz in quizzes %}
{{quiz.title}}
Total Questions - 10{{quiz.description|truncatewords:7}}
Start Quiz
{{quiz.created_at|timesince}} ago
{% endfor %}
{% else %}
No quiz available for this category
{% endif %}
< /code>
{ % condblock body %} < /p>
from django.shortcuts import render
from django.contrib.auth.decorators Импорт login_required
from .models import Quiz, категория
from django.db.models. /> Создайте свои представления здесь. < /h1>
@login_required (login_url = 'login')
def all_quizzes_view (запрос): < /p>
quizzes = Quiz.objects.order_by('-created_at')
categories = Category.objects.all()
context = {"quizzes" : quizzes, "categories" : categories}
return render(request, 'all-quizzes.html', context)
< /code>
@login_required (login_url = 'login')
def cat_search_view (request, category):
print ("Просмотр запуска") < /p>
# search by category
if category != " ":
quizzes = Quiz.objects.filter(category__name=category).order_by('-created_at')
# In category__name, category is the ForeignKey field in the Quiz model. Category (uppercase) is the model name. category__name accesses the name field inside the related Category model with the help of ForeignKey category field.
else:
quizzes = Quiz.objects.order_by('-created_at')
# print(quizzes)
categories = Category.objects.all()
context = {"categories" : categories, "quizzes" : quizzes}
return render(request, 'all-quizzes.html', context)
< /code>
@login_required (login_url = 'login')
def search_view (request): < /p>
# print("View triggered")
q = request.GET.get('q', '') # Get the search query (None if no query is provided)
if q:
quizzes = Quiz.objects.filter(Q(title__icontains=q) | Q(description__icontains=q)).order_by('-created_at')
else:
quizzes = Quiz.objects.all().order_by('-created_at') # Show all quizzes if no query
categories = Category.objects.all()
# Define the context dictionary only once
context = {
"quizzes": quizzes,
"categories": categories,
"query": q
}
return render(request, 'all-quizzes.html', context)
Подробнее здесь: https://stackoverflow.com/questions/794 ... e-search-c
Мобильная версия