【问题标题】:Using Django template logic to determine if a object gets shown or not使用 Django 模板逻辑来确定对象是否被显示
【发布时间】:2020-11-08 19:02:33
【问题描述】:

我希望如果用户选择 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>

models.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

我如何知道用户当前选择了什么选项?

【问题讨论】:

    标签: html python-3.x django django-models django-templates


    【解决方案1】:

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

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

    1. 在您的视图中,返回一个查询集返回每个帖子但过滤掉私人帖子。那也是documented
    2. 将剩余的帖子呈现到您的模板中。

    【讨论】:

      【解决方案2】:

      您可以为这样的公开帖子返回查询集。

      Post.objects.filter(post_public='Public')
      

      对于私人帖子也是如此:

      Post.objects.filter(post_public='Not public')
      

      【讨论】:

      • 我选择你的解决方案。工作得非常好!谢谢
      猜你喜欢
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      相关资源
      最近更新 更多