我的models.py是
class Question(models.Model):
question_text = models.CharField(max_length= 100)
pub_date = models.DateTimeField('Date Is Published')
image = models.ImageField(upload_to="Question_Image", blank=True)
def __str__(self):
return self.question_text
并且,我必须添加一个类"类别"所以我的每个问题都可以选择四个类别中的一个:世界,技术,屏幕和体育..例如,我的一个类别html我有screen.html我需要只显示基于类别'屏幕和#39 ;.这是我的screen.html。
{% extends 'polls/base.html' %}
{% block main_content %}
{% if latest_questions %}
<body>
<ul style="list-style: none;">
{% for question in latest_questions %}
<li style="float:center">
<div id="tabs"><a id="tabsword" href={% url 'polls:detail' question.id %}>
<img id="tabsimage" align="middle" src='{{question.image.url}}'/>
<p style=" font-size: 25px; font-family: Verdana; color: whitesmoke; text-align: center"><b>{{question.question_text}}</b></p>
</a>
</div>
</li>
{% endfor %}
</ul>
{% else %}
<p> You have no questions. Please add some.</p>
{% endif %}
{% endblock %}
帮助我修改代码,以便我可以添加班级类别,从四个类别中分配每个问题,并仅根据类别显示问题&#34;屏幕&#34;在上面的HTML。
答案 0 :(得分:0)
如果您不想为类别创建另一个模型,一种简单的方法是执行以下操作(从Django documentation字段选项开始):
from django.db import models
class Person(models.Model):
SHIRT_SIZES = (
('S', 'Small'),
('M', 'Medium'),
('L', 'Large'),
)
name = models.CharField(max_length=60)
shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
只需使用您想要的型号字段和选项替换衬衫尺码。
答案 1 :(得分:0)
没有办法这样做。 例如,在模型中定义选择
class Question(models.Model):
CATEGORY_SIZES = (
('W', 'WORlD'),
('T', 'TECHNOLOGY'),
('S', 'SCREEN'),
)
question_text = models.CharField(max_length= 100)
pub_date = models.DateTimeField('Date Is Published')
image = models.ImageField(upload_to="Question_Image", blank=True)
category = models.CharField(max_length=1, choices=CATEGORY_SIZES)
def __str__(self):
return self.question_text
在views.py
中def your_view(request):
questions = Question.objects.filter(category='S')
context = {'questions': questions}
return render(request, your_template ,context)
其他方式:如果您认为单独的模型将是您的更好选择
class Categories(models.Model):
name = models.CharField(max_length= 100)
def __str__(self):
return self.name
class Question(models.Model):
question_text = models.CharField(max_length= 100)
pub_date = models.DateTimeField('Date Is Published')
image = models.ImageField(upload_to="Question_Image", blank=True)
category = models.ForeignKey(Categories)
def __str__(self):
return self.question_text
在views.py
中def your_view(request):
category = Category.objects.get(name='Screen')
questions = category.question_set.all()
context = {'questions': questions}
return render(request, your_template,context)