Reputation: 801
I am making a form in which the user can edit their profile, so currently I have 2 forms, one that edits the User model(first_name, Username and Email) and other one that edits the Profile model(biography).
The problem is that every time I edit, just the User
model is the one that gets saved while the Profile model doesn't. I think that the error is in the views.py
file.
views.py
:
def edit_profile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
form1 = UpdateProfileForm(request.POST, instance=request.user)
if form.is_valid:
form.save()
form1.save()
return redirect('profile')
else:
form = EditProfileForm(instance=request.user)
form1 = UpdateProfileForm(instance=request.user)
args = {
'form': form,
'form1': form1,
}
return render(request, 'profile-edit.html', args)
forms.py
:
class EditProfileForm(UserChangeForm):
class Meta:
model = User
fields = (
'first_name',
'username',
'email',
)
exclude = ('password',)
class UpdateProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = (
'bio',
'profile_pic',
)
exclude = ('user',)
models.py
:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.CharField(max_length=400, default=1)
def __str__(self):
return f'{self.user.username} Profile'
profile-edit.html (I replaced the {{form.as_p}} and {{ form1.as_p }} to the following html code)
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="edit-profile">
<h3>Name</h3>
<input type="text" name="first_name" value="{{ user.first_name }}" maxlength="30" id="id_first_name">
<h3>Username</h3>
<input type="text" name="username" value="{{ user.username }}" maxlength="150" required="" id="id_username">
<h3>Bio</h3>
<input type="text" name="bio" value="{{ user.profile.bio }}" maxlength="400" id="id_bio">
<h3>Email</h3>
<input type="email" name="email" value="{{ user.email }}" maxlength="254" id="id_email">
<button type="submit">Submit</button>
</div>
</form>
Upvotes: 1
Views: 2165
Reputation: 801
I found the error on my code, i missed to pass the .profile from the model in the views.py file
Bad
form1 = UpdateProfileForm(request.POST, instance=request.user)
Good
form1 = UpdateProfileForm(request.POST, instance=request.user.profile)
Upvotes: 1