Django'如果没有'声明不能正常工作

时间:2016-06-07 01:16:44

标签: python django conditional

我正试图这样做,以便当我登录时,我的所有草稿都以红色字母显示DRAFT这个词,所以我尝试了以下

<h6 id="date">{% if post.draft %}<div id="draft">DRAFT</div>{% endif %} </h6>

但它不起作用,但如果我这样做

<h6 id="date">{% if post.publish %}<div id="draft">DRAFT</div>{% endif %} </h6>

它有效,而且既然有效,我认为使用'not'会起作用

<h6 id="date">{% if not post.publish %}<div id="draft">DRAFT</div>{% endif %} </h6>

但这不起作用。继承我的模特

class Post(models.Model):

  STATUS_CHOICES = (
     ('draft', 'Draft'),
     ('published', 'Published'),
  )
  title = models.CharField(max_length=250, unique=True)
  slug = models.SlugField(max_length=250,
                          unique_for_date='publish')
  image = models.ImageField(upload_to=upload_location,
                            null=True,
                            blank=True,
                            height_field='height_field',
                            width_field='width_field')
  image_url = models.CharField(max_length=500,
                               null=True,
                               blank=True,
                               )
  height_field = models.IntegerField(default=0,
                                     null=True,
                                     blank=True,
                                     )
  width_field = models.IntegerField(default=0,
                                    null=True,
                                    blank=True,
                                    )
  author = models.ForeignKey(User,
                             related_name='blog_posts',
                             null=True,
                             blank=True,)
  body = models.TextField(null=True, blank=True,)
  publish = models.DateTimeField(default=timezone.now)
  created = models.DateTimeField(auto_now_add=True)
  updated = models.DateTimeField(auto_now=True)
  status = models.CharField(max_length=10,
                            choices=STATUS_CHOICES,
                            default='draft')
  video = models.BooleanField(default=False)
  video_path = models.CharField(max_length=320,
                                null=True,
                                blank=True,)

  class Meta:
      ordering = ('-publish',)

  def __str__(self):
      return self.title

  def get_absolute_url(self):
      return reverse('blog:post_detail', kwargs={"slug": self.slug})

  objects = models.Manager() # The default manager.
  published = PublishedManager() # Our custom manager.
  tags = TaggableManager(blank=True)

这是我视图中的代码段

if request.user.is_staff or request.user.is_superuser:
    object_list = Post.objects.all().order_by('-id')
else:
    object_list = Post.published.all().order_by('-id')

为什么它与发布有关,但不是'if not post.publish'

1 个答案:

答案 0 :(得分:3)

在模板中,您应该使用:

{% if post.status == 'draft' %}

您的模型上有以下字段:

status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')

您只需要检查帖子状态&#39;字段值是否为草稿。

检查post.draft无法正常工作,因为没有字段draft