Django中自定义用户注册

78 阅读2分钟
  1. Django中创建自定义用户时,如何将自定义字段传递给create_user方法?
  2. 如何将自定义字段的值保存到数据库?

2. 解决方案

  1. 解决如何将自定义字段传递给create_user方法:

    在自定义用户模型中,可以使用create_user方法来创建新用户。但是,该方法只接收四个参数:usernamepasswordemailis_superuser。因此,我们需要创建一个自定义的create_user方法,以便能够将自定义字段的值传递给该方法。

    def create_user(self, username, password, email, **kwargs):
        user = User.objects.create_user(username, password, email)
        user.is_active = True
        user.customuser.school = kwargs.get('school', '-')  # 这里假设school字段是自定义字段之一
        user.customuser.birthdate = kwargs.get('birthdate', None)  # 这里假设birthdate字段是自定义字段之一
        user.customuser.sex = kwargs.get('sex', '-')  # 这里假设sex字段是自定义字段之一
        user.customuser.city = kwargs.get('city', None)  # 这里假设city字段是自定义字段之一
        user.customuser.save()
        return user
    
  2. 解决如何将自定义字段的值保存到数据库:

    在创建新用户后,可以使用save()方法将自定义字段的值保存到数据库。

    user = CustomUser.objects.create(
        user=user,
        school=fuser,
        birthdate=fbday,
        sex=fsex,
        city=fcity
    )
    

    这样,自定义字段的值就会被保存到数据库中。

代码示例

# models.py
class CustomUser(models.Model):
    school = models.CharField(max_length=30, blank=True, null=True)
    birthdate = models.DateField(blank=True, null=True)
    sex = models.CharField(max_length=1, blank=True, null=True)
    city = models.CharField(max_length=30, blank=True, null=True)

    def create_user(self, username, password, email, **kwargs):
        user = User.objects.create_user(username, password, email)
        user.is_active = True
        user.customuser.school = kwargs.get('school', '-')  # 这里假设school字段是自定义字段之一
        user.customuser.birthdate = kwargs.get('birthdate', None)  # 这里假设birthdate字段是自定义字段之一
        user.customuser.sex = kwargs.get('sex', '-')  # 这里假设sex字段是自定义字段之一
        user.customuser.city = kwargs.get('city', None)  # 这里假设city字段是自定义字段之一
        user.customuser.save()
        return user

# views.py
def registration(request):
    if request.method == 'POST':
        form = Registration(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            fuser = cd['username']
            fpassword = cd['password']
            femail = cd['email']
            fschool = cd['school']
            fbday = cd['birthdate']
            fsex = cd['sex']
            fcity = cd['city']

            user = CustomUser.objects.create_user(fuser, fpassword, femail, school=fschool, birthdate=fbday, sex=fsex, city=fcity)

            user.is_active = True
            user.save()
            return HttpResponseRedirect("/home/")
    else:
        form = Registration()
    return render(request, "registration.html", {'form': form})

# forms.py
class Registration(forms.Form):
    school_choices = (('MS', 'Middle School'), ('HS', 'High school'), ('U', 'University'), ('-', 'Not defined'),)
    sex_choices = (('M', 'Male'), ('F', 'Female'), ('-', 'Not defined'),)

    username = forms.CharField(label='Username')
    password = forms.CharField(label='Password', widget=forms.PasswordInput)
    repassword = forms.CharField(label='Reinstert password', widget=forms.PasswordInput)
    email = forms.EmailField()
    school = forms.ChoiceField(choices=school_choices, required=False, label='What school are you enrolled?')
    birthdate = forms.DateField(label='Birth date', required=False)
    sex = forms.ChoiceField(choices=sex_choices, required=False, label='Sex')
    city = forms.CharField(label='City', required=False)

    def clean_repassword(self):
        repassword = self.cleaned_data['repassword']
        password = self.cleaned_data['password']
        if repassword != password:
            raise forms.ValidationError("Verification password different from original password!")

    widgets = {
        'password': forms.PasswordInput(),
    }