[英]Django is it better to check user.is_authenticated in views.py or in template?
I have a homepage, which I want to display a login form when user is not logged in or display a list of items belong to that user if he/she already logged in. 我有一个主页,我想在用户未登录时显示登录表单,或者如果他/她已登录则显示属于该用户的项目列表。
So far I came up with 2 methods: 到目前为止,我想出了两种方法:
Check whether user is authenticated in views.py and render corresponding view (in my views.py ): 检查用户是否在views.py中进行了身份验证并呈现相应的视图(在我的views.py中 ):
if request.user.is_authenticated(): return render(request, 'items.html') else return render(request, 'login.html')
Check directly in template and generate corresponding HTML for each case (in my index.html ): 直接检查模板并为每个案例生成相应的HTML(在我的index.html中 ):
{% if user.is_authenticated %} HTML for my items list {% else %} HTML for my login form {% endif %}
So which method is better for handling this? 那么哪种方法更适合处理这个? Are those methods differ much in performance?
这些方法的性能差异很大吗? Is there any standard that we should handling these in views.py or in template itself?
我们应该在views.py或模板本身处理这些标准吗?
I don't think there is a big performance difference. 我不认为有很大的性能差异。 What's most important is how much you should stick to
MVC
pattern. 最重要的是你应该坚持多少
MVC
模式。
A template
is meant to just display some sort of data that the view
provides. template
仅用于显示view
提供的某种数据。 Any kind of logic like deciding what kind of data to show based on requester's state should always be implemented by the view. 任何类型的逻辑,例如决定基于请求者状态显示什么类型的数据,应始终由视图实现。 Thus, you should move your logic into view function for the cleanness of your design.
因此,您应该将逻辑移动到视图功能中,以保证设计的清洁。
Logic should be in your python code, not your template as much as possible.
逻辑应该在你的python代码中,而不是你的模板尽可能多。 Due to maintenance and future-proof reasons .
由于维护和未来的原因 。
It depends on your html. 这取决于你的HTML。 If you want to change only a little part of your code based on the condition, check inside a template:
如果您只想根据条件更改代码的一小部分,请检查模板内部:
{% if user.is_authenticated %}
<h3>Welcome</h3>
{% else %}
<a href="/path/to/login">Login</a>
{% endif %}
But if items.html
and login.html
are different and big templates, you should definitely do the login inside your view. 但是如果
items.html
和login.html
是不同的大模板,那么你一定要在视图中进行登录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.