Не понимаю почему не сохраняется фото при добавление его пользователем.
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
location = models.CharField(max_length = 4, null=True, blank = True)
phone = models.CharField(max_length = 11, null=True, blank = True)
image = models.ImageField(blank=True, upload_to='user_images',
default='user_images/default-user.png')
forms.py
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('phone', 'location', 'image')
views.py
@login_required
def edit_profile(request, username):
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
profile_form = ProfileForm(request.POST, instance=request.user.profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(
request,
"Информация профиля успешно отредактирована!"
)
return HttpResponseRedirect(reverse('profile', kwargs={'username': request.user.username}))
else:
user = User.objects.get(username=username)
user_form = UserForm(instance=user)
profile_form = ProfileForm(instance=user.profile)
return render(request, 'account/profile_edit.html', {
'user_form': user_form,
'profile_form': profile_form
})
@login_required
def view_profile(request, username):
user = User.objects.get(username=username)
return render(request, 'account/profile.html', {'user': user,})
profile.html
<div class="col s6">
<h3>{{ user.last_name }} {{ user.first_name }}</h3>
<p>Email: {{ user.email }}</p>
<p>Телефон: {{ user.profile.phone }}</p>
<p>Кабинет: {{ user.profile.location }}</p>
</div>
<div class="col s6">
{% if user.profile.image %}
<img height="350" width="300" src="{{ user.profile.image.url }}">
{%else%}
<p></p>
{%endif%}
</div>
<a href="{% url 'edit_profile' username=request.user.username %}">Изменить профиль</a></li>
</div>
profile_edit.html
<form method="post">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<button type="submit">Сохранить изменения</button>
</form>