django:我可以在 html 模板中编写 python 吗?

标签 django django-templates

{% if request.session["user_name"] %}
<div class="abcd">user has username</div>
{% else %}
<div class="abcd">user doesn't has username</div>
{% endif %}

这是违法的吗?有错误:

TemplateSyntaxError at /users/register/submit

Could not parse the remainder: '['user_name']' from 'request.session['user_name']'

最佳答案

Django 文档说:

Django template system is not simply Python embedded into HTML

这意味着您不能编写 Python。

但是谈论变量,doc还说:

Behind the scenes

Technically, when the template system encounters a dot, it tries the following lookups, in this order:

  • Dictionary lookup
  • Attribute lookup
  • Method call
  • List-index lookup

这意味着您正在尝试的是可能的,但正确的语法是:

{% if request.session.user_name %}

关于django:我可以在 html 模板中编写 python 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4094135/

相关文章:

Django 在 S3ResponseError : 301 Moved Permanently 中收集静态结果

具有多个实例的 Django 应用程序 - 如何确保每日电子邮件仅发送一次?

jquery - 如何将 jQuery slider 的值保存到 Person 模型中?

django - 如何在 Django 管理中的字段旁边添加自定义按钮?

javascript - jquery 数据丢失时数据表消失

python - 命令 'python' 未找到 - 在我将其指定为 python3 的别名之后

python - 在抛出断言 IntegrityError 的单元测试后进行清理

django - 如何从模板标签中的模型对象获取 django 模型字段值

re_path 的 Django 模板 url NoReverseMatch

python - 正确使用 Django FormPreview