我正在设置一个表单,并希望允许用户编辑(清除或上传)他们的个人资料图片。当个人资料图片中没有文件时,我遇到了 ValueError-属性没有与之关联的文件。
这是一些代码 Models.py
class UserProfile(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
profile_picture = models.ImageField(upload_to='profile_image', blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True,)
def __str__(self):
return self.user.email
forms.py
class EditProfileForm(ModelForm):
first_name = forms.CharField(
label='firstname',
widget=forms.TextInput(attrs={
'name': 'firstname',
'id': 'firstname',
'class': 'form-control'
})
)
last_name = forms.CharField(
label='lastname',
widget=forms.TextInput(attrs={
'name': 'lastname',
'id': 'lastname',
'class': 'form-control'
})
)
class Meta:
model = UserProfile
fields = (
'first_name',
'last_name',
'profile_picture'
)
def save(self, user=None):
user_profile = super(EditProfileForm, self).save(commit=False)
if user:
user_profile.User = user
user_profile.save()
return user_profile
views.py
def user_edit(request):
title = "profile suno.space"
heading = "Your account"
context = {
'title': title,
'heading': heading,
}
if request.method == 'POST':
form = EditUserForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect(reverse('accounts:view_profile'))
else:
form = EditUserForm(instance=request.user)
context['form'] = form
return render(request, 'accounts/user_edit.html', context)
模板
<form id="account-form" method="post" enctype="multipart/form-data" class="form">
{% csrf_token %}
<div class="form-controls">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="profile_picture" class="form-label">Your profile picture</label>
<div>{{ form.profile_picture }}</div>
</div>
</div>
</div>
</div>
</form>
我希望模板能够像管理模板那样呈现浏览按钮。