如何根据Django中的用户类型限制对页面的访问

编程入门 行业动态 更新时间:2024-10-20 13:41:37
本文介绍了如何根据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中的用户类型限制对页面的访问

本文发布于:2023-10-24 19:55:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524854.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   页面   用户   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!