【发布时间】:2018-10-06 23:48:28
【问题描述】:
我目前正在创建一个允许用户查看和编辑他们自己的个人资料的应用程序。我最近添加了用户将个人资料图片添加到其个人资料的功能。我可以在管理页面中添加一个配置文件,它会显示在选定的用户配置文件上没问题。问题是当用户尝试更新他们的图片时,我得到一个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>
【问题讨论】:
标签: python html django django-forms django-views