1

방금 ​​Subscription이라는 django에서 AbstractBaseUser 및 PermissionsMixin을 상속하는 사용자 정의 사용자 모델을 만들었습니다. 그런 다음 관리 콘솔에 내 사용자 정의 사용자 모델을 등록하기 위해 admin.py 파일에 필요한 양식 클래스를 서브 클래 싱했습니다.Django - 관리 콘솔에서 사용자 정의 사용자 모델에 대한 권한 및 그룹을 할당하는 기능

먼저 사용자 정의 사용자 모델과 권한 및 그룹이 장고에 어떻게 어울리는 지 혼란 스럽습니다. 내 사용자 모델에 PermissionsMixin을 전달한 후 manage.py migrate 스크립트를 실행했고 데이터베이스에 두 개의 새 테이블을 만들었습니다. subscriber_conf_subscriber_groupssubscriber_conf_subscriber_user_permissions. 또한 django documentation에는 그룹 모델이 admin에서 등록되지 않은 예제가 주어 졌으므로이를 수행했습니다.

이제 관리 콘솔에서 구독자를 편집하고 & 가입자를 편집하기위한 양식이 있습니다. 내 질문은, 관리 콘솔에서 내 구독자에게 사용 권한 및 그룹을 할당하는 기능을 어떻게 추가합니까? 새 사용자 모델이 아직 내장 된 장고 사용 권한 및 그룹과 관련되어 있습니까? 아니면 코드화해야하는 항목입니까?

모든 설명이 훌륭합니다.

models.py 당신의 SubscriberAdmin 클래스에서

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

는 다음과 같이 당신의 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

저자는 스크린 샷에서 '구독자'아래의 '그룹'링크에 대해 묻습니다. 귀하의 답변은 페이지에 '그룹'상자를 추가하는 방법을 보여줍니다. 여기서 admin은 새로운 사용자를 추가 할 수 있습니다. – TitanFighter

0

조금 늦게하지만 다른 사람 들어,은이

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

및 필드 셋에

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

을 시도 왜 그룹을 사용하는 경우 한 가지 더 Admins에서 그룹화하고 두 번째 그룹으로 새 사용자에게 그룹을 할당 할 수 있습니다. 이게 도움이 되길 바란다! 안부 전해 주시기 바랍니다.