简体   繁体   中英

Django sign up view how to get the user from the user form to assign profile to the user

I have this sign up form where I am taking values from the user about his username and password and also his proile. I have separately created two forms UserForm and ProfileForm . When the user is signing up for his account how do I connect profile to the user.

This is what I have

forms.py

class SignUpForm(UserCreationForm):

    email = forms.EmailField(required=True,
                         label='Email',
                         error_messages={'exists': 'Oops'})
    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")

        def save(self, commit=True):
            user = super(SignUpForm, self).save(commit=False)
            user.email = self.cleaned_data["email"]
            # user.status = self.cleaned_data["status"]
            if commit:
                user.save()
            return user


class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['contact', 'whatsapp', 'gender', 'avatar']

models.py

class Profile(models.Model):
    STATUS_CHOICES = (
    (1, ("Permanent")),
    (2, ("Temporary")),
    (3, ("Contractor")),
    (4, ("Intern"))
    )
    GENDER_CHOICES = (
    (1, ("Male")),
    (2, ("Female")),
    (3, ("Not Specified"))
    )
    PAY_CHOICES = (
    (1, ("Fixed")),
    (2, ("Performance Based")),
    (3, ("Not Assigned")),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    emp_type = models.IntegerField(choices=STATUS_CHOICES, default=1)
    start_date = models.DateField(default=timezone.now)
    end_date = models.DateField(null=True, blank=True)
    user_active = models.BooleanField(default=True)
    contact = models.CharField(max_length=13, blank=True)
    whatsapp = models.CharField(max_length=13, blank=True)
    gender = models.IntegerField(choices=GENDER_CHOICES, default=3)
    pay_type = models.IntegerField(choices=PAY_CHOICES, default=3)
    pay = models.IntegerField(default=0)
    avatar = models.ImageField(upload_to='users/images', default='users/images/default.jpg')
    title = models.CharField(max_length=25, unique=False)
    #manager_username = models.ForeignKey(User, blank=True, null=True, to_field='username',related_name='manager_username', on_delete=models.DO_NOTHING)

    def __str__(self):
        return self.user.username


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

views.py

def createAccount(request):
    if(request.method == 'POST'):
        u_form = SignUpForm(request.POST) # fill it with user details
        p_form = ProfileForm(request.POST, request.FILES)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            profile = p_form.save(commit=False)
            profile.user = u_form.user
            p_form.save()
            messages.success(request, f'Account Updated')
            return redirect('createAccount')
    return render(request, 'mainapp/createAccount.html')

When I am creating a new user with his profile information. I am getting an error

AttributeError at /create
'SignUpForm' object has no attribute 'user'
Request Method: POST
Request URL:    http://localhost:8000/create
Django Version: 2.1
Exception Type: AttributeError
Exception Value:    
'SignUpForm' object has no attribute 'user'
Exception Location: C:\Users\Himanshu Poddar\Desktop\ATG IInternship\INTRANET\atg-intranet\Intranet\users\views.py in createAccount, line 23
Python Executable:  C:\Users\Himanshu Poddar\AppData\Local\Programs\Python\Python36-32\python.exe
Python Version: 3.6.2

I think this is the part where I am going wrong, My question is how do I connect the user to his profile while signing up.

u_form.save()
profile = p_form.save(commit=False)
profile.user = u_form.user

How can I resolve this?

profile.user = u_form.user is indeed causing problems here.

You try to access the user created by the SignupForm , but it is not set as a property of the form, but returned by the save method.

To fix this, you'll need to capture the user created by the SignUpForms's save method. Change the block where you create the user and profile to this:

...
user = u_form.save()
profile = p_form.save(commit=False)
profile.user = user
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM