将名字和姓氏添加到Django-Registration

3

我在项目中使用了默认的Djangoregistration(版本0.8),其中用户只需输入用户名、电子邮件和密码。然而,我希望用户在注册页面上也能输入他们的名字和姓氏。如何轻松实现这个功能呢?


你可以在这个帖子中看到一个简单的解决方案: https://dev59.com/JHM_5IYBdhLWcg3wcCnc - kelwinfc
1个回答

1
你可以覆盖默认的UserRegisterForm并创建一个新的字段来覆盖它。
创建一个名为forms.py的新文件。在你的视图中导入并使用这个表单。
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User

class UserRegisterForm(UserCreationForm):
    username = forms.CharField(max_length = 100)
    email  = forms.EmailField(max_length = 100)
    password1 = forms.CharField(widget = forms.PasswordInput() , max_length = 100)
    password2 = forms.CharField(widget = forms.PasswordInput(),  max_length = 100)
    first = forms.CharField(max_length = 100 )
    last = forms.CharField(max_length = 100)

    class Meta  : 
        fields = "__all__"
        
    def clean_username(self):
        username = self.cleaned_data.get("username")
        if not username : 
            raise forms.ValidationError("UserName cannot be empty !")

        try : 
            user = User.objects.get(username = username)
        except :
            user = None

        if user : 
            raise forms.ValidationError("User with the username -: {} already exits ".format(username))

        return username    

    def clean_first(self) :
        first = self.cleaned_data.get("first")
        if not first: 
            raise forms.ValidationError("Kindly enter your first name !")
            
    def clean_last(self) :
        last = self.cleaned_data.get("last")
        if not last: 
            raise forms.ValidationError("Kindly enter your last name !")

    # in what ever field you want to apply validations and authentications create a function named "clean_{field_name}" and get the data from the cleaned_data attribute .
    


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接