When I submit a sign up form which contains information for the user (username, email, password) and the user profile (first name and last name) and call save like form.save()
and profileform.save()
in my views.py then all seems to be fine and I get no errors.
However, when I go into the Django Admin then I see that the user profile and the profile have saved separately.
So there's two different profiles, one containing the username I entered into the form, and the other with first and last name (as the image displays).
Here's my views.py:
def signup(request):
if request.method == 'POST':
form = UserRegistrationForm(data=request.POST)
profileform = UserRegistrationProfileForm(data=request.POST)
if form.is_valid() and profileform.is_valid():
user = form.save()
profileform.save()
if user is not None:
if user.is_active:
user_login(request, user, backend='django.contrib.auth.backends.ModelBackend')
return redirect('/dashboard/')
else:
form = UserRegistrationForm()
profileform = UserRegistrationProfileForm()
return render(request, 'signup-user.html', {'form': form, 'profileform': profileform})
Forms.py (for the profile part of the form):
class UserRegistrationProfileForm(forms.ModelForm):
user_fname = forms.CharField(#)
user_lname = forms.CharField(#)
class Meta:
model = UserProfileModel
fields = ['user_fname', 'user_lname']
def clean(self):
#...
def save(self, commit=True):
profile = super(UserRegistrationProfileForm, self).save(commit=False)
if commit:
profile.save()
return profile
Models.py (for the profile, which includes the receiver signal):
class UserProfileModel(models.Model): # For the Company Employees
user = models.OneToOneField(UserModel, related_name='userprofilemodel', on_delete=models.CASCADE, blank=True, null=True)
user_fname = models.CharField(max_length=30, verbose_name='First Names')
user_lname = models.CharField(max_length=30, verbose_name='Last Name')
class Meta:
verbose_name = 'Profile'
def __unicode__(self):
#...
def save(self, *args, **kwargs):
super(UserProfileModel, self).save(*args, **kwargs)
@receiver(post_save, sender=UserModel)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfileModel.objects.create(user=instance)
@receiver(post_save, sender=UserModel)
def save_user_profile(sender, instance, **kwargs):
instance.userprofilemodel.save()
Am not sure what I'm doing wrong? I want the form to create ONE user profile that has the user instance as user, as well as the first and last name.
Any ideas on where i'm going wrong?
Update
Here's the UserRegistrationForm
class:
class UserRegistrationForm(forms.ModelForm):
#
class Meta:
model = UserModel
fields = ['related_company_slug', 'username', 'user_email', 'password', 'passwordrepeat']
def clean(self):
#
def save(self, commit=True):
self.check_company
user = super(UserRegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data.get('password'))
user.is_active = True
if commit:
user.save()
return user