I want to add fields to django.contrib.auth forms. Is there anyway to do that?
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 [This is my models.py file]
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 is basically the ACCOUNT_FORMS signup and I am using django allauth forms but I cant figure out how to add a field to it eg phone number.
To add a field into your form, you'd have to add the same field in the model, because that form is creating a new object from the django.contrib.auth
User model. You can achieve this in many ways, the easiest being creating a new User model that has a ForeignKey pointing to the Django one. I'd recommend you to take a look at this question or the official Django docs regarding this topic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.