Django简单标记在条件不起作用

时间:2016-09-18 11:00:37

标签: django django-templates

我想通过使用审核工具添加块来自定义django-admin的视频对象更改表单。

当我在if条件下使用自定义简单标签时 - 它不起作用。

models.py:

class Video(models.Model):

    class Meta:
        db_table = 'video'

    DRAFT = 1
    MODERATION = 2
    PUBLISHED = 3
    REJECTED = 4
    HOSTING_UPLOADING = 5
    SUSPICIOUS = 6

    PUBLICATION_STATUSES = (
        (DRAFT, 'draft'),
        (MODERATION, 'moderation'),
        (PUBLISHED, 'published'),
        (HOSTING_UPLOADING, 'hosting uploading'),
        (REJECTED, 'rejected'),
        (SUSPICIOUS, 'suspicious')
    )

    video_pk = models.AutoField(primary_key=True)
    name = models.CharField(max_length=150, blank=True)
    hosting_id = models.CharField(max_length=20, blank=True)
    publication_status = models.PositiveSmallIntegerField(choices=PUBLICATION_STATUSES, default=MODERATION)

templatetags video_publication_statuses.py:

from api.models import Video
from django import template

register = template.Library()

@register.simple_tag
def moderation(status):
    return status == Video.MODERATION


@register.simple_tag
def suspicious(status):
    return status == Video.SUSPICIOUS


@register.simple_tag
def published(status):
    return status == Video.PUBLISHED


@register.simple_tag
def hosting_uploading(status):
    return status == Video.HOSTING_UPLOADING


@register.simple_tag
def rejected(status):
    return status == Video.REJECTED

change_form.html:

{% extends "admin/change_form.html" %}
{% load video_publication_statuses %}
{% suspicious original.publication_status as suspicious_status %}
{% moderation original.publication_status as moderation_status %}
{% hosting_uploading original.publication_status as hosting_uploading_status %}
{% published original.publication_status as published_status %}
{% rejected original.publication_status as rejected_status %}

{% block after_related_objects %}
  {% if original.pk %}
    {% for fieldset in adminform %}
      {% if fieldset.name == 'Moderation' %}
        {% include "admin/includes/fieldset.html" %}
      {% endif %}
    {% endfor %}
    <div class="submit-row">
      {% if rejected_status or moderation_status or suspicious_status %}
        <input type="submit" value="Publish" name="publish" >
      {% endif %}
      {% if published_status %}
        <input type="submit" value="Reject" name="reject" >
      {% endif %}
    </div>
  {% endif %}
{% endblock %}

当我使用显式值而不是标签时,它可以工作:

  {% if original.publication_status == 3 %}
    <input type="submit" value="Reject" name="reject" >
  {% endif %}

请帮我理解标签有什么问题?

1 个答案:

答案 0 :(得分:3)

我相信这种情况正在发生,因为模板标签会传递字符串,而您会根据整数来检查字符串,例如return "3" == 3

从广义上讲,你在模板中放了很多逻辑,我通常会避免这种情况。模板标签保留用于&#34;表示逻辑&#34;我认为这意味着改变某些东西的呈现方式,而不是改变观看的东西。该逻辑属于视图或模型本身。

将这个逻辑放在你的模型上应该很容易。

class Original(...):
  def rejected(self):
    return self.status == Video.rejected