В настоящее время я создаю приложение, которое позволяет пользователям просматривать и редактировать свой личный профиль. Я недавно добавил в возможность для пользователя добавить изображение профиля в свой профиль. Я могу добавить профиль на странице администратора, и он будет отображаться в профиле выбранных пользователей без проблем. Проблема в том, что когда пользователь пытается обновить свою картинку, я получаю сообщение ValueError
, сообщающее, что с атрибутом image
не связано ни одного файла. Ниже описано, как я пытался реализовать функциональность
Модель
class UserProfileModel(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
age = models.PositiveIntegerField(blank=True, null=True)
email = models.EmailField(max_length=254, null=True, blank=True, unique=True)
height = models.PositiveIntegerField(blank=True, null=True)
weight = models.PositiveIntegerField(blank=True, null=True)
bio = models.CharField(max_length=100, blank=True, default='')
image = models.ImageField(upload_to='profile_image', blank=True)
Форма
class UpdateProfile(forms.ModelForm):
class Meta:
model = UserProfileModel
fields = ('email', 'age', 'height', 'weight', 'bio', 'image')
вид
def update_profile(request):
args = {}
if request.method == 'POST':
form = UpdateProfile(request.POST, instance=request.user.userprofilemodel)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('account:profile'))
# return render(request, 'account/profile.html')
else:
form = UpdateProfile()
if request.user.is_authenticated():
form = UpdateProfile(instance=request.user.userprofilemodel)
args['form'] = form
return render(request, 'account/edit_profile.html', args)
HTML
<!DOCTYPE html>
<html>
<body>
{#<h2 style="text-align:center">User Profile Card</h2>#}
<div class="container">
<h1>{{ user }}s Profile </h1>
<div style="margin: 24px 0;">
<p>Username: {{ user }}</p>
<p>Email: {{ user.userprofilemodel.email }}</p>
<p>Age: {{ user.userprofilemodel.age }}</p>
<p>Height: {{ user.userprofilemodel.height }} CM </p>
<p>Weight: {{ user.userprofilemodel.weight }} KG </p>
<p>User Bio: {{ user.userprofilemodel.bio }} </p>
<img src="{{ user.userprofilemodel.image.url }}" width="240">
</body>
</html>