0

I am really new to django. I have a model and 2 forms like this below extending the User model. The UserProfile is linked to the user model which would be where I have my extra field. I have seen numerous posts but still was't able to solve it. I would like to save the profile with additional parameters like the phone number stated below when the registration form is submitted, I have been spending hours trying to make it work, thanks a lot for your help in advance:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length = 50)
    phone_number = models.CharField(max_length=12)

#In form.py

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ['username',
                  'first_name',
                  'last_name',
                  'email',
                  'password1',
                  'password2'
                  ]
    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.email = self.cleaned_data['email']

        if commit:
            user.save()

        return user

class RegistrationFormProfile(forms.ModelForm):
    phone_number = forms.CharField(max_length = 12)

    class Meta:
        model = UserProfile
        fields = [
              'phone_number',
              ]
    def save(self, commit=True):

        profile.phone_number = self.cleaned_data['phone_number']

        if commit:
            profile.save()

        return profile
#In views.py
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        profileForm = RegistrationFormProfile(request.POST)
        if form.is_valid():
            user = form.save()
            if(profileForm.is_valid()):
                profileForm.save()
                return redirect('accounts/profile')
        else:
            return redirect('accounts/wrong')
    else:
        form = RegistrationForm()
        profileForm = RegistrationFormProfile()
        args = {'form' : form, 'profileForm' : profileForm}
        return render(request, 'users/reg_form.html', args)
soulless
  • 383
  • 1
  • 5
  • 18
  • Check this [link](https://stackoverflow.com/questions/2601487/django-registration-django-profile-using-your-own-custom-form/3298481#3298481), if it helps. – Bijoy Oct 17 '17 at 09:03
  • Your link requires use of other libraries? Are there ways to do it natively? – soulless Oct 17 '17 at 09:12
  • Got another https://stackoverflow.com/questions/11512972/django-2-models-1-form – Bijoy Oct 17 '17 at 09:16
  • That's the problem. The second form (profile) has 1 to 1 relationship with the user model, it can't be done by simply calling save.. – soulless Oct 17 '17 at 09:22

0 Answers0