首页 > 解决方案 > 使用 Django 模板逻辑来确定对象是否被显示

问题描述

如果用户选择作为他的下拉选项,我希望能够Not public不显示该帖子,如果它Public被显示。

index.html 的代码:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    {% for post_object in object_list %}
      {% if post_object.choices == "Public" %}
        <h1>{{ post_object.post_title }}</h1>
        <p>{{ post_object.post_description }}</p>
      {% else %}
      {% endif %}
    {% endfor %}
  </body>
</html>

模型.py代码:

class Post(models.Model):
    post_title = models.CharField("Post title", max_length=200)
    post_description = models.TextField("Small description of your post")
    post_summary = models.TextField("Post summary")
    post_public = models.CharField(max_length=300, choices=[('Not public', 'Not public'), ('Public', 'Public')], default="Not public")

    def __str__(self):
        return self.post_title

我怎么知道用户选择的当前选项?

标签: htmlpython-3.xdjangodjango-modelsdjango-templates

解决方案


我只是假设您不需要前端表单,如您的标题中所述。我不会为你完成你的观点,但我会给你如何做到这一点的指导方针。

回到主题,首先在后端处理所有事情会更容易,因为随着事情变得复杂,Python 比 Jinja2 模板语法强大得多。

  1. 在您的视图中,返回一个查询集,该查询集返回每个帖子但过滤掉私人帖子。这也被记录在案
  2. 将剩余的帖子渲染到您的模板中。

推荐阅读