How to create a UserProfile form in Django with first_name, last_name modifications?

前端 未结 7 1293
挽巷
挽巷 2020-11-29 19:55

If think my question is pretty obvious and almost every developer working with UserProfile should be able to answer it.

However, I could not find any he

7条回答
  •  無奈伤痛
    2020-11-29 20:46

    This is something i used in one my projects long back hopefully it should help out the others googling this problem .

    class SignUpForm(forms.ModelForm):
        first_name = forms.CharField(max_length = 30)
        last_name = forms.CharField(max_length = 30)
        username = forms.CharField(max_length = 30)
        password = forms.CharField(widget = forms.PasswordInput)
        password1 = forms.CharField(widget = forms.PasswordInput)
        class Meta:
            model = UserProfile
            exclude = ['user']
    
        def clean_username(self): # check if username does not exist before
            try:
                User.objects.get(username=self.cleaned_data['username']) #get user from user model
            except User.DoesNotExist :
                return self.cleaned_data['username']
    
            raise forms.ValidationError("This user exist already choose an0ther username")
    
    
    
        def clean(self, *args , **kwargs):
            super(SignUpForm).clean(*args ,**kwargs) # check if password 1 and password2 match each other
            if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:#check if both pass first validation
                if self.cleaned_data['password1'] != self.cleaned_data['password2']: # check if they match each other
                    raise forms.ValidationError("Passwords don't match each other")
    
            return self.cleaned_data
        def save(self): # create new user
            new_user = User.objects.create_user(username=self.cleaned_data['username'],password=self.cleaned_data['password1'],email=self.cleaned_data['email'])
            new_user.first_name = self.cleaned_data['first_name']
            new_user.last_name = self.cleaned_data['last_name']
            new_user.save()
            UserProf =  super(SignUpForm,self).save(commit = False)
            UserProf.user = new_user
            UserProf.save()
            return UserProf
    

提交回复
热议问题