在Django-Registration中添加名字和姓氏

3 投票
1 回答
1925 浏览
提问于 2025-04-17 11:09

我在我的项目中使用了默认的Django registration(版本0.8),用户只需要输入他们的用户名、电子邮件和密码。不过,我希望用户在注册页面上也能输入他们的名字和姓氏。我该怎么简单地做到这一点呢?

1 个回答

1

你可以做的是覆盖默认的用户注册表单,然后创建一个新的字段来替代它。

新建一个文件,命名为 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 .
    

撰写回答