Django TemplateSyntaxError求助:无法解析request.session['userType']
解决Django TemplateSyntaxError:无法解析剩余部分: '[userType]' from '[userType]'
这个错误的根源是Django模板不支持Python字典的索引语法(['key']),你在模板里写的request.session['userType']违反了模板的语法规则,所以才会触发解析失败。
修复方法:
把模板里的字典索引写法改成Django模板支持的格式,有两种可选方式:
方式1:使用点符号访问session键
修改你的模板代码如下:
{% if 'is_logged_in' in request.session %} {% if request.session.userType == 0 %} {% include 'headersuccess.html' %} {% else %} dfgh {% endif %} {% endif %}
方式2:使用get方法(更安全,避免键不存在时抛出错误)
如果担心userType可能不存在于session中,可以用get方法设置默认值,避免意外报错:
{% if 'is_logged_in' in request.session %} {% if request.session.get('userType', -1) == 0 %} {% include 'headersuccess.html' %} {% else %} dfgh {% endif %} {% endif %}
额外优化建议:
你也可以在视图层把userType直接传到模板上下文里,这样模板代码会更简洁直观。比如修改index视图:
@csrf_exempt def index(request): context = {} if('is_logged_in' in request.session): id = request.session['authToken'] # 从session中取出userType加入上下文 context['uid'] = id context['userType'] = request.session.get('userType', -1) return render(request,"index.html", context);
然后模板里就可以直接用:
{% if is_logged_in %} {% if userType == 0 %} {% include 'headersuccess.html' %} {% else %} dfgh {% endif %} {% endif %}
这样既符合Django的最佳实践,也让模板代码更易读维护。
内容的提问来源于stack exchange,提问作者med
相关产品推荐
相关产品推荐

