Как вы называете форму добавления пользователя по умолчанию для настраиваемого администратора? - PullRequest
1 голос
/ 03 марта 2020

Я создал настроенную форму изменения User Admin, но когда я создаю нового пользователя, он переходит в форму Change. Форма добавления базового администратора соответствует тому, что я хочу, поэтому я хочу оставить ее? Кроме того, как мне зашифровать пароль, как только я вернусь обратно в форму создания администратора базы? Как мне это изменить?

Admin.py:

from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin

from .forms import UserAdminChangeForm
from .models import User

# Register your models here.

User=get_user_model()

class UserAdmin(admin.ModelAdmin):
    form = UserAdminChangeForm
    search_fields=['username','user_type']
    list_display=('username','full_name','password','email','user_type','ad','pqa','ts','tl','tm','stm','active')

    list_filter = ('ad',)
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        ('Personal info', {'fields': ('full_name','birth_date','hire_date',)}),
        ('Permissions', {'fields': ('ad','tm','pqa','stm','ts','tl')}),
    )


    class Meta:
        model = User

admin.site.register(User,UserAdmin)

forms.py:

from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from .models import User


class RegisterForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)
    usertype= forms.Select(choices=User.USER_TYPE_CHOICES)

    class Meta:
        model = User
        fields = ('username',)

    def clean_username(self):
        username = self.cleaned_data.get('username')
        qs = User.objects.filter(username=username)
        if qs.exists():
            raise forms.ValidationError("Username is taken")
        return username

    def clean_password2(self):
        # Check that the two password entries match
        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(RegisterForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
            return user



class UserAdminCreationForm(forms.ModelForm):
    """
    A form for creating new users. Includes all the required
    fields, plus a repeated password.
    """
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
    usertype= forms.Select(choices=User.USER_TYPE_CHOICES)

    class Meta:
        model = User
        fields = ['username','password','user_type']

    def clean_password2(self):
        # Check that the two password entries match
        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):
        # Save the provided password in hashed format
        user = super(UserAdminCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UserAdminChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = User
        fields = ('username', 'password', 'active', 'ad')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]

Я очень ценю помощь. ТИА

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...