英文:
Premium and regular users in django
问题
在Django中,我想区分用户模型,有高级用户和普通用户。我该如何实现这一点,应该在用户类中还是有其他方法?
英文:
I want to differentiate the users model, have premium and regular users. How do I implement that in Django, should it be in the users class or is there another approach ?
答案1
得分: 2
以下是翻译好的内容:
有两种相对简单的方法。第一种是使用群组 - 在这里查看群组文档:
可以为群组分配权限,然后您可以检查这些权限。这样,您只需将用户添加到群组,而不是为每个用户分配单独的权限。当存在许多不同的权限集时,这是特别有用的。然后,您可以按照此问题检查用户是否属于某个群组,或者检查特定权限。
如果没有涉及许多其他权限,您可能希望简单地向自定义用户添加一个字段(文档建议始终使用自定义用户),例如:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
is_premium = models.BooleanField(default=False)
然后在您的settings.py中添加以下内容:
AUTH_USER_MODEL = '<myapp>.CustomUser'
AbstractUser是一个类,用于允许您扩展普通用户而不会破坏其他任何内容。有了这个字段,您可以轻松进行测试,例如:
if request.user.is_premium:
英文:
There's two relatively simple ways. The first is groups - see the groups docs here:
Groups can be assigned permissions that you can then check for. That way you only need to add the user to the group, rather than assigning each user each permission. This is especially useful when there are lots of different permissions sets. Then you can check if a user belongs to a group as per this question, or check for specific permissions.
If there's not a lot of other permissions involved, you might want to simply add a field to a Custom User, (the docs recommend always using a custom user) eg:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
is_premium = models.BooleanField(default=False)
And then adding the following in your settings.py
AUTH_USER_MODEL = '<myapp>.CustomUser'
AbstractUser is a class set up to allow you to extend the normal user without breaking anything else. With that field you can easily test, for example:
if request.user.is_premium:
答案2
得分: 1
你实际上已经可以使用现有的功能来实现这个。Django 已经有了用户组,你可以给用户组附加权限。
这意味着你可以定义一个名为“premium”的用户组,例如将权限附加到该用户组,非高级用户将无法拥有这些权限。然后你可以将用户添加到该组中。
欲了解更多信息,请阅读文档中的权限和授权部分。
英文:
You can actually already do that with the available functionalities. Django already has groups, and you can attach permissions to groups.
This thus means that you can define a group named "premium" and for example attach permissions to that premium group that non-premium users will not have. Then you can add users to that group.
For more information, read the permissions and authorization section of the documentation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论