Hi all,
[edited based on feedback from this post: User + User Profile update with Class Based View - #7 by MarekH]
This is my first post here.
I’m following the tutorial by pythontutorial.net. It ends with an implementation for adding a user profile to users and creating an edit form for both the user model and the profile model. For this it implements a ModelFor and uses it in a in an updateview. The problem I’m facing is that the form element from the template somehow doesn’t end-up in the final page source. However all elements within the form are displayed. The result of this is that the submit is no longer working as intended (it somehow calls logout which I also don’t understand).
I’ve found a way to mitigate the issue by adding a empty form element above the actual form. This way the entire page works as intended.
forms.py
...
class ProfileUpdateForm(forms.ModelForm):
email = forms.EmailField(required=True,
widget=forms.TextInput(attrs={'class': 'form-control'}))
avatar = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control-file'}))
class Meta:
model = UserProfile
fields = ['avatar']
views.py
class UpdateProfile(LoginRequiredMixin, UpdateView):
template_name = 'users/profile.html'
model = UserProfile
form_class = ProfileUpdateForm
def get_object(self):
return self.request.user.userprofile
def form_valid(self, form):
profile = form.save()
user = profile.user
user.email = form.cleaned_data['email']
user.save()
return redirect('profile')
templates/users/profile.html
{% extends 'base.html' %}
{% block content %}
<div class="center">
<!-- <form></form>
adding an empty leading form solves the problem for some reason -->
<form method="post" enctype="multipart/form-data" novalidate class="card">
{% csrf_token %}
<label for="email">Email address:</label>
<input type="text" id="email" name="email" value="{{ user.email }}">
<label for="avatar">Avatar:</label>
<input type="file" id="avatar" name="avatar">
<button type="submit" class="btn btn-primary full-width">Update Profile</button>
</form>
</div>
{% endblock content %}
Thank you for any support.