[Answered ]-How do I make a User Profile form using OnetoOneField extending the User Model?

1๐Ÿ‘

You can create both user and profile models at once using a generic create view.

Forms:

class UserProfileForm(forms.ModelForm):
class Meta:
    model = Profile
    fields = ["username", "name", "email", "paypal_id", "bio", "user"]

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

class Meta:
    model = User
    fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2']

View:

class CreateUserProfileView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
model = Profile
form_class = UserProfileForm
user_form_class = UserForm
template_name = 'accounts/account_create.html'
success_message = "Profile created successfully"
success_url = reverse_lazy('profile-list')

def get(self, request):
    profile_form = self.form_class()
    user_form = self.user_form_class()
    return render(request, self.template_name, {'profile_form': profile_form, 'user_form': user_form})

def post(self, request, *args, **kwargs):
    profile_form = self.form_class(request.POST)
    user_form = self.user_form_class(request.POST)
    if all([profile_form.is_valid(), user_form.is_valid()]):
        user = user_form.save()
        profile = profile_form.save(commit=False)
        profile.user = user
        profile.save()
        messages.success(request, self.success_message)
    else:
        return render(request, self.template_name, {'profile_form': profile_form, 'user_form': user_form})

    return HttpResponseRedirect(self.success_url)
๐Ÿ‘คAjay saini

0๐Ÿ‘

You need to overwrite save() method of Profile to create/update User on-the-fly while saving Profile.

I.e.:

class Profile(models.Model):

...

    def save(self, *args, **kwargs):

        if not self.user.pk:
            self.user = User.objects.create_user(self.user.username, password=self.user.password)

        self.user.save()  # mandatory as create_user is not recognized as save operation
        super().save(*args, **kwargs)
๐Ÿ‘คEgor Wexler

Leave a comment