我想向django.contrib.auth表单添加字段。反正有这样做吗?
from django.contrib.auth import get_user_model, forms
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
User = get_user_model()
client = Client(URL, API_KEY)
class UserChangeForm(forms.UserChangeForm):
class Meta(forms.UserChangeForm.Meta):
model = User
class UserCreationForm(forms.UserCreationForm):
error_message = forms.UserCreationForm.error_messages.update(
{
"duplicate_username": _(
"This username has already been taken."
)
}
)
class Meta(forms.UserCreationForm.Meta):
model = User
def clean_username(self):
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise ValidationError(
self.error_messages["duplicate_username"]
)
Models.py [这是我的models.py文件]
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
class User(AbstractUser):
# First Name and Last Name Do Not Cover Name Patterns
# Around the Globe.
name = models.CharField(
_("Name of User"), blank=True, max_length=255
)
phone= models.CharField(
_("Phone"), blank=True, max_length=20
)
def get_absolute_url(self):
return reverse(
"users:detail", kwargs={"username": self.username}
)
Usercreationform基本上是ACCOUNT_FORMS注册,并且我正在使用django allauth表单,但是我无法弄清楚如何在其中添加字段,例如电话号码。
答案 0 :(得分:0)
要将字段添加到表单中,您必须在模型中添加相同的字段,因为该表单正在根据django.contrib.auth
用户模型创建新对象。您可以通过多种方式实现这一目标,最简单的方法是创建一个新的User模型,该模型的ForeignKey指向Django。建议您看看有关该主题的this问题或official Django docs。