2014-12-03 22 views
1

我剛剛在django中創建了一個名爲Subscriber的自定義用戶模型,它繼承自AbstractBaseUser和PermissionsMixin。然後我在我的admin.py文件中將必要的表單類分類,以便使用管理控制檯註冊我的自定義用戶模型。Django - 在管理控制檯中爲自定義用戶模型分配權限和組的能力

首先,我對自定義用戶模型和權限和組在django中的組合方式有些困惑。我跑了manage.py傳遞PermissionsMixin到我的用戶模型後遷移腳本,它在我的數據庫中創建兩個新表subscriber_conf_subscriber_groupssubscriber_conf_subscriber_user_permissions。此外,在django documentation內有一個例子,其中組模型從管理員註銷,所以我也這樣做了。

現在在管理控制檯中,我剛剛有一個訂戶和表單列表,用於創建編輯訂戶的&。我的問題是,如何添加從管理控制檯爲我的訂戶分配權限和組的權限?新的用戶模型是否仍然與內置的django權限和組關聯,或者這是我必須編寫的東西?

任何澄清將是偉大的。

models.py

from django.db import models 
from django.contrib.auth.models import User 
from django.conf import settings 
from django.utils import timezone 
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin 

#Custom user manager 
class SubscriberManager(BaseUserManager): 


    def create_user(self, email, first_name, last_name, dti_id, street_address1, 
     street_address2, city, state, full_zip, phone_number, password=None): 

     #save 5 digit zip 
     tmp_zip = full_zip.split("-") 
     new_zip = tmp_zip[0] 

     return self._create_user(email, first_name, last_name, dti_id, street_address1, 
      street_address2, city, state, new_zip, full_zip, phone_number, 
      False, False, password, 0) 

    #utility function 
    def _create_user(self, email, first_name, last_name, dti_id, street_address1, 
     street_address2, city, state, zip_code, full_zip, 
     phone_number, is_superuser, is_staff, password=None, account_updated=0): 

     #define now 
     now = timezone.now() 

     if not email: 
      raise ValueError('Users must have an email address') 

     #use django to normalize the email address 
     email = self.normalize_email(email) 

     user = self.model(
      email = email, 
      first_name = first_name, 
      last_name = last_name, 
      dti_id = dti_id, 
      street_address1 = street_address1, 
      street_address2 = street_address2, 
      city = city, 
      state = state, 
      zip_code = zip_code, 
      full_zip = full_zip, 
      phone_number = phone_number, 
      account_updated = account_updated, 
      is_admin = is_staff, 
      is_active = True, 
      is_superuser = is_superuser, 
      date_joined = now, 
      last_modified = now) 
     user.set_password(password) 
     user.save(using=self._db) 

     return user 

    #create superuser override 
    def create_superuser(self, email, first_name, last_name, dti_id, street_address1, 
     street_address2, city, state, full_zip, phone_number, password): 

     #either need to create needed fields or require them in user model 

     tmp_zip = full_zip.split("-") 
     new_zip = tmp_zip[0] 

     return self._create_user(email, first_name, last_name, dti_id, street_address1, 
      street_address2, city, state, new_zip, full_zip, phone_number, 
      True, True, password, 0) 


#Custom user definition 
class Subscriber(AbstractBaseUser, PermissionsMixin): 
    email = models.EmailField(max_length=254, unique=True, db_index=True) 
    first_name = models.CharField(max_length=100) 
    last_name = models.CharField(max_length=100) 
    dti_id = models.IntegerField(default=0) 
    street_address1 = models.CharField(max_length=100) 
    street_address2 = models.CharField(max_length=100, blank=True) 
    city = models.CharField(max_length=100) 
    state = models.CharField(max_length=10) 
    zip_code = models.CharField(max_length=5) 
    full_zip = models.CharField(max_length=10, blank=True) 
    account_updated = models.BooleanField(default=0) 
    phone_number = models.CharField(max_length=20) 

    last_modified = models.DateTimeField(default=timezone.now) 
    date_joined = models.DateTimeField(default=timezone.now) 
    is_active = models.BooleanField(default=True) 
    is_admin = models.BooleanField(default=False) 

    objects = SubscriberManager() 

    USERNAME_FIELD = 'email' 

    REQUIRED_FIELDS = [ 
     'first_name', 
     'last_name', 
     'dti_id', 
     'street_address1', 
     'street_address2', 
     'city', 
     'state', 
     'full_zip', 
     'phone_number', 
    ] 

    # define custom perms 
    class Meta: 
     permissions = (
      ("view_web", "Can access SJ web content"), 
      ("view_web_e_edition", "Can access SJ e-edition content"), 
      ("view_wweb", "Can access weekly web content"), 
      ("view_wweb_e_edition", "Can access weekly e-edition content"), 

      #.... more permissions 
      #may be able to use this for subscriber coupons and such 
     ) 

    def get_full_name(self): 
     return self.email 

    def get_short_name(self): 
     return self.email 

    def __unicode__(self): 
     return self.email 

    def has_perm(self, perm, obj=None): 
     return True 

    def has_module_perms(self, app_label): 

     return True 

    @property 
    def is_staff(self): 
     return self.is_admin 

admin.py

from django import forms 
from django.contrib import admin 
from django.contrib.auth.models import Group 
from django.contrib.auth.admin import UserAdmin 
from django.contrib.auth.forms import ReadOnlyPasswordHashField 

from subscriber_conf.models import Subscriber 


class SubscriberCreationForm(forms.ModelForm): 

    password1 = forms.CharField(label='Password', widget=forms.PasswordInput) 
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) 

    class Meta: 
     model = Subscriber 
     fields = (
      'email', 
      'first_name', 
      'last_name', 
      'dti_id', 
      'street_address1', 
      'street_address2', 
      'city', 
      'state', 
      'zip_code', 
      'full_zip', 
      'phone_number', 
     ) 

    def clean_password2(self): 
     password1 = self.cleaned_data.get("password1") 
     password2 = self.cleaned_data.get("password2") 
     if password1 and password2 and password1 != password2: 
      raise forms.ValidationError("Passwords don't match") 
     return password2 

    def save(self, commit=True): 
     user = super(SubscriberCreationForm, self).save(commit=False) 
     user.set_password(self.cleaned_data["password1"]) 

     #perhaps do some stuff with times and dates 

     if commit: 
      user.save() 
     return user 


class SubscriberChangeForm(forms.ModelForm): 
    password = ReadOnlyPasswordHashField() 

    class Meta: 
     model = Subscriber 
     fields = (
      'email', 
      'password', 
      'first_name', 
      'last_name', 
      'dti_id', 
      'street_address1', 
      'street_address2', 
      'city', 
      'state', 
      'zip_code', 
      'full_zip', 
      'phone_number', 
      'account_updated', 
      'is_admin', 
      'is_active', 
      'is_superuser', 
      'date_joined', 
      'last_modified' 
      ) 

    def clean_password(self): 
     return self.initial["password"] 


class SubscriberAdmin(UserAdmin): 
    form = SubscriberChangeForm 
    add_form = SubscriberCreationForm 

    date_hierarchy = 'last_modified' 


    list_display = ('email', 'first_name', 'last_name', 
    'street_address1', 'street_address2', 'city', 'state', 
    'zip_code', 'full_zip', 'phone_number', 'dti_id', 'account_updated', 
    'last_modified', 'is_admin', 'is_superuser') 
    list_filter = ('is_admin', 'is_superuser', 'account_updated',) 
    fieldsets = (
     (None, {'fields': ('email', 'password')}), 
     ('Personal info', {'fields': ('first_name', 'last_name', 'street_address1', 
      'street_address2', 'city', 'state', 'zip_code', 'full_zip', 
      'phone_number', 'account_updated',)}), 
     ('Permissions', {'fields': ('is_admin',)}), 
    ) 

    add_fieldsets = (
     (None, { 
      'classes': ('wide',), 
      'fields': ('email', 'first_name', 'last_name', 'street_address1', 'street_address2', 
      'city', 'state', 'full_zip', 'phone_number', 'password1', 'password2')} 
     ), 
    ) 
    search_fields = ('email', 'street_address1', 'street_address2', 'first_name', 
     'last_name',) 
    ordering = ('dti_id',) 
    filter_horizontal =() 


admin.site.register(Subscriber, SubscriberAdmin) 
admin.site.unregister(Group) 

My django admin console

回答

-1

在你SubscriberAdmin類更改field_sets和add_fieldsets像下面這樣。在權限中包含組。

fieldsets = (
    (None, {'fields': ('name', 'password')}), 
    ('Personal info', {'fields': ('email', 'phone', 'civilId', 'address',)}), 
    ('Permissions', {'fields': ('groups',)}), 
) 
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin 
# overrides get_fieldsets to use this attribute when creating a user. 
add_fieldsets = (
    (None, { 
     'classes': ('wide',), 
     'fields': ('name', 'email', 'password1', 'password2', 'phone', 
      'civilId', 'address', 'groups',)} 
    ), 
    ('Permissions', {'fields': ('groups',)}), 
) 

在權限中包含組。還有一件事,如果你正在使用羣體,爲什麼註銷組

+0

作者詢問關於屏幕截圖上的'Subscribers'下的'Groups'鏈接。您的answear會顯示如何將「羣組」框添加到該頁面,其中管理員可以添加新用戶。 – TitanFighter 2016-08-13 23:46:17

0

有點晚,但對於其他人,試試這個

#admin.site.unregister(Group) <-- comment this line 

和字段集

('Permissions', {'fields': ('is_admin','is_staff','groups',)}) 

隨着第一,您可以管理來自管理員的組和第二個可以將組分配給新用戶。我希望這有幫助! 問候!

相關問題