简体   繁体   English

如何将字段添加到 django.contrib.auth forms

[英]How to add field to django.contrib.auth forms

I want to add fields to django.contrib.auth forms.我想向 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] 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 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. Usercreationform 基本上是 ACCOUNT_FORMS 注册,我正在使用 django allauth forms 但我不知道如何向其中添加字段,例如电话号码。

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. 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.您可以通过多种方式实现此目的,最简单的方法是创建一个新用户 model,该用户的 ForeignKey 指向 Django 之一。 I'd recommend you to take a look at this question or the official Django docs regarding this topic.我建议您查看这个问题或有关此主题的 官方 Django 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM