【发布时间】:2019-05-18 10:15:43
【问题描述】:
执行下面代码的结果
{{p.category}} <!-- help -->
{% if p.category == "help" %}
<button type="button" class="btn btn btn-outline-danger btn-sm" style="color:blue;">
<a href="{% url "todo:todo_help" p.pk %}" >help 11</a>
</button>
{% else %}
<button type="button" class="btn btn btn-outline-danger btn-sm">
<a href="{% url "todo:todo_help" p.pk %}" >help 22 </a>
</button>
{% endif %}
我希望输出 help11 按钮。
原因是 {{p.category} 是 'help'
但输出按钮是 help22。
我不知道为什么这不起作用
这个比较逻辑错了吗?
如果你知道原因,请告诉我。
查看
class TodoList(LoginRequiredMixin,ListView):
model = Todo
paginate_by = 20
def get_queryset(self):
if self.request.user.is_anonymous:
return Todo.objects.all().order_by('-created')
else:
return Todo.objects.filter(Q(author=self.request.user) & Q(elapsed_time__isnull=True)).order_by('-created')
def get_context_data(self, *, object_list=None, **kwargs):
context = super(TodoList, self).get_context_data(**kwargs)
context['comment_form'] = CommentForm()
context['category_list'] = Category.objects.all()
context['todos_without_category'] = Todo.objects.filter(category=None).count()
context['todo_count_uncomplete'] = Todo.objects.filter(Q(author=self.request.user) & Q(elapsed_time__isnull=True)).count()
context['todo_count_complete'] = Todo.objects.filter(Q(author=self.request.user) & Q(elapsed_time__isnull=False)).count()
context['total_todo_count_uncomplete'] = Todo.objects.filter(Q(elapsed_time__isnull=True)).count()
context['total_todo_count_complete'] = Todo.objects.filter(Q(elapsed_time__isnull=False)).count()
return context
models.py(类别字段)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL)
类别模型
class Category(models.Model):
name = models.CharField(max_length=25, unique=True)
description = models.TextField(blank=True)
slug = models.SlugField(unique=True, allow_unicode=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'categories'
def get_absolute_url(self):
return '/todo/category/{}/'.format(self.slug)
【问题讨论】:
-
只是为了调试:如果你写
if str(p.category) == "help",会发生什么? -
您的类别可能是带有
name的Category对象?你能分享你的Category模型吗?可能支票是{% if p.category.name == ... %}。 -
@WillemVanOnsem 哦,我明白了。 :) 我认为它是一个 Python。
-
@HyK:视图没那么有趣,有趣的部分是
Category模型。 -
@HyK 你应该使用
{% if p.category.name== "help" %}确实
标签: django if-statement templates