Django管理员网站似乎忽略了自定义UserCreationForm

时间:2018-03-30 03:16:48

标签: django django-admin

我有一个Django项目Project,我试图在其中包含UserProfile模型的自定义用户信息。我创建了一个自定义StackedInlineUserCreationFormUserAdmin,以便在创建用户时添加此信息,但Django管理网站中的表单不会受到影响。

# Commons/admin.py

class ProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'Profile'
    fk_name = 'user'


class UserProfileCreationForm(UserCreationForm):
    phone = forms.RegexField(
        regex=r'^\+?1?\d{9,15}$',
        error_messages={'invalid': "Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."},
        required=True
    )
    phone2 = forms.RegexField(
        regex=r'^\+?1?\d{9,15}$',
        error_messages={'invalid': "Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."},
        required=False
    )
    address = forms.CharField()

    class Meta:
        model = User
        fields = '__all__'

    def save(self, commit=True):
        if not commit:
            raise NotImplementedError("Can't create User and UserProfile without database save")
        user = super(UserProfileCreationForm, self).save(commit=True)
        user_profile = UserProfile(
            user=user,
            phone=self.cleaned_data['phone'],
            phone2=self.cleaned_data['phone2'],
            address=self.cleaned_data['address']
        )
        user_profile.save()
        return user, user_profile


class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline, )
    add_form = UserProfileCreationForm
    add_fieldsets = (
    (None, {
        'classes': ('wide',),
        'fields': ('username', 'password1', 'password2', 'phone', 'phone2', 'address')
    }),
)

    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

我在Commons注册了INSTALLED_APPS个应用,是否还有其他我缺失的内容?

编辑:

# urls.py
urlpatterns = [
    re_path(r'^admin/?', admin.site.urls),
    re_path(r'^jwt-auth/', obtain_jwt_token),
    re_path(r'^.*', TemplateView.as_view(template_name="Commons\index.html"), name='base')
]

0 个答案:

没有答案