我正在尝试覆盖广告页面的更改模型表单,但不知道为什么它不起作用。 smb可以帮我吗?
我的forms.py:
from django import forms
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth.models import User
class CustomUserChangeForm(UserChangeForm):
email = forms.EmailField(required=True, label="Email")
phone = forms.CharField(label="Phone number")
class Meta:
model = User
fields = ("username", "email", "phone", )
我的管理员:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'username', 'phone', ]
admin.site.register(CustomUser, CustomUserAdmin)
我的模型。py
class CustomUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(_('username'), max_length=30,
unique=True)
first_name = models.CharField(_('first name'), max_length=30,
blank=True)
last_name = models.CharField(_('last name'), max_length=30,
blank=True)
email = models.EmailField(_('email address'), unique=True,
blank=True, null=True)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the
format: '+999999999'. Up to 15 digits allowed.")
phone = models.CharField(_('phone number'), validators=[phone_regex],
max_length=17,
unique=True, blank=True, null=True)
我正在尝试覆盖变更模型表单,但是不知道为什么它不起作用。 smb可以帮我吗?
答案 0 :(得分:1)
乍一看,您在表格中使用了错误的模型:应该是
from myapp.models import CustomUser
from django.contrib.auth.forms import UserChangeForm
class CustomUserChangeForm(UserChangeForm):
email = forms.EmailField(required=True, label='Email')
phone = forms.CharField(label='Phone number')
class Meta:
model = CustomUser
fields = ('username', 'email', 'phone', )
话虽如此,由于您的CustomerUserChangeForm
没有任何字段可以更改密码或权限,因此您可以使用简单的ModelForm
[Django-doc]:
from django.forms import ModelForm
from myapp.models import CustomUser
class CustomUserChangeForm(ModelForm):
email = forms.EmailField(required=True, label='Email')
phone = forms.CharField(label='Phone number')
class Meta:
model = CustomUser
fields = ('username', 'email', 'phone', )