简体   繁体   English

Django:向 UserCreationForm 添加其他字段

[英]Django: Add additional fields to UserCreationForm

Can we add additional fields to UserCreationForm in django.我们可以在 django 中的 UserCreationForm 中添加其他字段吗?

By default there are 5 fields in UserCreationForm:默认情况下,UserCreationForm 中有 5 个字段:

  1. username用户名
  2. email email
  3. first_name
  4. last_name
  5. password密码

If I want to add additional fields like age, gender then how can I add these in UserCreationForm.如果我想添加其他字段,例如年龄、性别,那么如何在 UserCreationForm 中添加这些字段。

I am new to django any reference or descriptive code will be appreciable.我是 django 的新手,任何参考或描述性代码都会很明显。

Do This As Per The Link根据链接执行此操作

class SignUpForm(UserCreationForm):
    # My Own Custom Fields
    username = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}))
    first_name = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), max_length=32, help_text='First name')
    last_name=forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}), max_length=32, help_text='Last name')
    email=forms.EmailField(forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'}), max_length=64, help_text='Enter a valid email address')
    password1=forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}))
    password2=forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password Again'}))

    # The Default Fields Of The UserCreation Form
    class Meta(UserCreationForm.Meta):
        model = User
        # I've tried both of these 'fields' declaration, result is the same
        # fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
        fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',)

If you wish to store information related to User, you can use a OneToOneField to a model containing the fields for additional information.如果您希望存储与用户相关的信息,您可以使用 OneToOneField 到包含附加信息字段的 model。

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    additional_field1 = models.SomeField()
    .....

Read the docs here for the details on extending the user model.阅读此处的文档,了解有关扩展用户 model 的详细信息。

There are a few steps we need to follow, step 1: Inherit the UserCreationForm and add custom form fields to it, as per your case in forms.py我们需要遵循几个步骤,第 1 步:继承 UserCreationForm 并向其添加自定义表单字段,根据您在forms.py中的情况

class SignUpForm(UserCreationForm):
    age = forms.IntegerField()
    gender = forms.CharField()

    class Meta:
        model = User
        fields = ['username', 'age', 'gender', 'password1', 'password2']

step 2: Create a model as per your custom fields and create a OneToOneField relation with User in models.py file第 2 步:根据您的自定义字段创建 model 并在models.py文件中创建与 User 的 OneToOneField 关系

from django.contrib.auth.models import User

class UserData(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    age = models.PositiveIntegerField()
    gender = models.CharField(max_length=20)

step 3: create a view that will invoke during POST method and will create a new user instance and will store the extra field data to the model which we created第 3 步:创建一个将在 POST 方法期间调用的视图,并将创建一个新的用户实例并将额外的字段数据存储到我们创建的 model

def register_user(request):
    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            age = form.cleaned_data.get('age')
            gender = form.cleaned_data.get('gender')
            user = User.objects.get(username=username)
            user_data = UserData.objects.create(user=user, age=age, gender=gender)
            user_data.save()
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'base/signupform.html', {'form':form})

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

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