我有一個功能來檢查用戶是否是員工:
class VerificateUser():
def allowed_user(request):
if request.user.is_staff:
return True
在我的模板中,我將只為員工用戶顯示此部分,但這不起作用。
{% url if not allowed_user %}
<h1>
Welcome to the show
</h1>
If do something like it, works:
```html
{% if not request.user.is_staff %}
<h1>
Welcome to the show
</h1>
但我需要使用視圖函式來清理我的代碼,因為我可能要添加更多條件。
uj5u.com熱心網友回復:
由于您使用的是基于類的視圖,因此我建議更新context您可以在html模板中使用的字典以確定是否user允許。例如,在views.py.
class VerificateUser():
# Update the context
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Call the allowed_user() and return whatever value, passing that value it to the context variable
context['allowed_user'] = self.allowed_user()
return context
# Checking if the user is allowed here
def allowed_user():
if self.request.user.is_staff:
return True
return False
現在在html檔案中,您可以allowed_user從背景關系變數中參考它。
{% if allowed_user %}
<h1>Hi, you are allowed to see here...</h1>
{% endif %}
這應該夠了吧。
uj5u.com熱心網友回復:
您可以通過多種方式進行此類操作,但您可以通過以下方式進行 -
{% if request.user.is_authenticated %}
<p>Welcome,{{request.user.first_name}} </p>
{% endif %}
request默認情況下,物件在所有 Django 模板背景關系中都可用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529150.html
標籤:Pythondjango
