如何根据Django中的用户类型限制对页面的访问 [英] How to restrict access to pages based on user type in Django

查看:193
本文介绍了如何根据Django中的用户类型限制对页面的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本问题,对新的Django开发人员可能有用。

I have a basic question which can be useful for new Django developers.

我在Django中创建了自己的UserProfile。该UserProfile有一个称为类型的特定字段。此字段可以有两个值(直到现在,将来可能更多):男性-男/女性-女:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆