如何在django中为自定义用户添加组?

时间:2016-04-30 23:03:15

标签: python django django-models django-authentication django-custom-user

我使用此官方文档创建了自定义用户模型customizing authentication in Django 但是如何添加群组和提交?我的django是版本1.9

2 个答案:

答案 0 :(得分:7)

您可以使用PermissionsMixin(https://docs.djangoproject.com/es/1.9/topics/auth/customizing/#custom-users-and-permissions

将组和权限与自定义用户模型一起使用

只需使用您的自定义用户模型继承PermissionsMixin:

var Shape = function(sides) {
  (sides < 3 || typeof sides !== 'number') ? this.sides = 0 : this.sides = Math.floor(sides);
};

Shape.prototype.getType = function(){
  var shapes = {0: "not defined shape", 3: "triangle", 4: "quadrilateral", 5: "pentagon", 6: "hexagon", 7: "heptagon", 8: "octagon", 9: "nonagon", 10: "decagon"};
  return shapes[this.sides];
}

var square = new Shape(7);
document.write("<pre> I am a " + square.getType() + "</pre>");

然后您可以使用与默认django.contrib.auth用户模型完全相同的方式访问它。

答案 1 :(得分:1)

TL;博士

('Group Permissions', {
    'fields': ('groups', 'user_permissions', )
})

详细说明

在 admin.py 中添加这个

app/admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import App


class AppAdminConfig(UserAdmin):
    # ordering, list_display, etc..
    
    fieldsets = (
        # Other fieldsets

        ('Group Permissions', {
            'classes': ('collapse',),
            'fields': ('groups', 'user_permissions', )
        })
    )


admin.site.register(App, AppAdminConfig)

如果有人对整个代码的外观感兴趣,请参阅 this