html - 使用 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
我怎么知道用户选择的当前选项?
解决方案
我只是假设您不需要前端表单,如您的标题中所述。我不会为你完成你的观点,但我会给你如何做到这一点的指导方针。
回到主题,首先在后端处理所有事情会更容易,因为随着事情变得复杂,Python 比 Jinja2 模板语法强大得多。
- 在您的视图中,返回一个查询集,该查询集返回每个帖子但过滤掉私人帖子。这也被记录在案。
- 将剩余的帖子渲染到您的模板中。
推荐阅读
- c - VS Code(Code Runner):接受 c 程序的用户输入
- plotly-express - 如何使用 Plotly Express 将符号序列映射到变量?
- javascript - 红绿灯问题。单击时切换颜色
- javascript - 仅清除画布的某些组件
- python - 数据框到 PostgreSQL 数据库
- javascript - 在密码字段内放置密码可见性图标
- java - 每当我运行一个简单的空手道功能时,就会用 thymeleaf 调试日志发送垃圾邮件
- javascript - 如何为图标使用变量
- css - 打字稿:单击“X”没有成功关闭我的弹出横幅
- magento2 - 如何从magento 2中的可配置产品中获取简单产品