如何根据 Django 中的用户类型限制对页面的访问 [英] How to restrict access to pages based on user type in Django
问题描述
我有一个基本问题,对新的 Django 开发人员很有用.
I have a basic question which can be useful for new Django developers.
我在 Django 中创建了自己的 UserProfile.此用户配置文件有一个名为类型"的特定字段.此字段可以有两个值(直到现在可能将来会更多):男性 - M/女性 - F :
I created my own UserProfile in Django. This UserProfile has a specific field called 'type'. This field can have two values (until now maybe more in the future) : Male - M / Female - F :
from django.contrib.auth.models import User
GENDER = (
(M, 'Male'),
(F, 'Female'),
)
class UserProfile(models.Model):
user = models.OneToOneField(User)
type = models.CharField( max_length=2,
choices=GENDER,
default='F')
基本上,我希望允许访问以限制访问或根据用户类型调整页面内容.到目前为止,我使用了一种非常基本和初学者的方法,即在视图中测试用户类型,然后处理页面:
Basically, I wanted to allow access to restrict access or to adapt page content depending on user Type. Until now, I used a really basic and beginner approach which is to test user type in a view and then process the page:
def OnePage(request):
if request.user.type == 'M':
....
else if request.user.type =='F':
....
然后我还需要根据用户类型调整呈现的模板:男性用户不会拥有与女性用户相同的个人资料页面.
Then I also need to adapt the template rendered depending on user type: a male user will not have the same profile page that a Female User.
我确信有更好的方法可以做到这一点,但作为一个 Django 初学者,我完全迷失了 Django 的所有可能性.因此,如果您有任何最佳实践来实现这一点,请告诉我(显然我想要一个可以在每个视图上使用的 DRY 代码!)
I am sure there are better ways to do this but as a Django beginner I am quite lost with all of Django possibilities. So if you have any best practices to implement this please tell me (obviously I would like a DRY code I could use on every view!)
感谢您的帮助.
推荐答案
一种解决方案可能是根据用户类型更改基本模板名称:
One solution could be to change the base template name depending on the user type:
@render_to('some_template.html')
def some_view(request):
base_template = 'base_%s.html' % request.user.profile.type
# …
return {
'base_template': base_template,
}
在你的模板中:
{% extends base_template %}
{% block some-block %}
…
{% endblock %}
如果您需要对每个视图都执行此操作,您可以使用中间件来设置此值.
If you need to do this on every view, you could use a middleware to set this value.
这篇关于如何根据 Django 中的用户类型限制对页面的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!