如何为投票应用添加分类类,实现问题分类及screen分类问题展示
Got it, let's break this down step by step to get your feature working exactly how you want it.
Step 1: Add the Category class to your models.py
First, we'll create a Category model with your four predefined options, then link it to your existing Question model so each question is tied to one category. Here's the code to add:
from django.db import models # Add this Category model above your Question model class Category(models.Model): CATEGORY_CHOICES = [ ('world', 'World'), ('technology', 'Technology'), ('screen', 'Screen'), ('sports', 'Sports'), ] name = models.CharField(max_length=20, choices=CATEGORY_CHOICES, unique=True) def __str__(self): return self.get_name_display() # Shows the human-readable name, e.g., "Screen" instead of "screen" # Update your existing Question model to include the category foreign key class Question(models.Model): # ... keep all your existing fields here (like title, content, pub_date, etc.) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='questions') def __str__(self): return self.title
After adding this, don't forget to run migrations to update your database:
python manage.py makemigrations python manage.py migrate
Step 2: Update your view to fetch only 'Screen' category questions
Next, modify the view that renders screen.html to pull only questions tagged with the 'screen' category. Here's how to do it with a function-based view:
from django.shortcuts import render, get_object_or_404 from .models import Category, Question def screen_view(request): # Get the 'screen' category (returns 404 if it doesn't exist) screen_category = get_object_or_404(Category, name='screen') # Fetch all questions in this category, ordered by most recent first screen_questions = Question.objects.filter(category=screen_category).order_by('-pub_date') return render(request, 'screen.html', {'questions': screen_questions})
If you're using a class-based ListView, override the get_queryset method instead:
from django.views.generic import ListView from .models import Question class ScreenQuestionListView(ListView): model = Question template_name = 'screen.html' context_object_name = 'questions' def get_queryset(self): return Question.objects.filter(category__name='screen').order_by('-pub_date')
Step 3: Modify screen.html to display the filtered questions
Update your template to loop through the questions variable we passed from the view. Here's a simple example you can adapt to your existing styling:
<h1>Screen Category Questions</h1> {% if questions %} <div class="question-list"> {% for question in questions %} <div class="question-card"> <h2>{{ question.title }}</h2> <p>{{ question.content }}</p> <small>Posted on {{ question.pub_date|date:"F j, Y" }}</small> </div> {% endfor %} </div> {% else %} <p>No questions in the Screen category yet—be the first to add one!</p> {% endif %}
That's all you need! Once you implement these changes, your screen.html page will only show questions tagged with the 'screen' category, and you'll be able to assign any of the four categories to questions via the Django admin or your custom forms.
内容的提问来源于stack exchange,提问作者arpan mahatra

