开发者

How to create a permissions table independent of the user permissions in Django?

开发者 https://www.devze.com 2023-03-12 19:36 出处:网络
I want to create a permission table that takes dja开发者_StackOverflow社区ngo-users and another table as its foreign key . And then gives permissions to it. What should be there in models.py ?

I want to create a permission table that takes dja开发者_StackOverflow社区ngo-users and another table as its foreign key . And then gives permissions to it . What should be there in models.py ?

The doubt can be put across as two separate questions :

  1. How to use django-users (user id) as a foreign key in another app called permissions .
  2. How to use table-id that is generated by django when syncdb is done as the priamry key of

that table (Different app) , to be used as foreign key of this app permissions .


Is there a reason you can't use the permissions features in django.contrib.auth? By using the permissions feature of the Meta object and the Groups table, you can easily create a matrix of "users in group X may perform action Y".

The more I think about this, the more it seems that your implementation would mirror the Groups/permissions feature without extra benefits.

See https://docs.djangoproject.com/en/1.3/topics/auth/ for details.


Your best best is to create a User Profile - which is a model that can be linked to the User model, where the Profile model contains whatever keys you want. Then you can call User.get_profile(), and get a model object, check what keys it has.


For the model, you want to look at the ContentTypes app in .contrib. (https://docs.djangoproject.com/en/1.3/ref/contrib/contenttypes/) and you can just create a foreign key to the user.

from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType

class Permission(models.Model):
    user = models.ForeignKey(User)
    table = models.ForeignKey(ContentType)
    ### the rest of the model.

Then in your view or whatever:

perm = Permission()
perm.user = request.user
perm.table = ContentType.objects.get_for_model(TableToAddPermissionFor)
perm.save()
0

精彩评论

暂无评论...
验证码 换一张
取 消