在我的应用中,我允许用户拥有个人资料照片。我希望他们能够改变它。令人惊讶的是,我没有找到任何关于如何实现这一目标的内容。
以下是我的尝试:
models.py
class UserProfile(FacebookProfileModel):
user = models.OneToOneField(User)
profilepic = models.ImageField(upload_to="profilepics/", default="blabla.jpg")
我的HTML:
<form method='post' action='{%url myproject.views.changes %}>
<div class="controls">
<input type="file" name="image">
</div>
<input type="submit">
</form>
我的观点:
def changes(request):
if 'image' in request.POST:
image = request.POST.get('image')
userprofile.profilepic.url = image
userprofile.save()
当我这样做时,收到以下错误消息:
'AttributeError at /my/site/
can't set attribute'
关于如何实现这一点的任何想法?谢谢
答案 0 :(得分:1)
确保首先请求UserProfile对象,然后
看起来应该使用
image = request.FILES['image']
userprofile.profilepic = image
而不是
image = request.POST.get('image')
userprofile.profilepic.url = image
请参阅This example,views.py部分,如杰克所说
答案 1 :(得分:1)
您需要在表单中包含enctype="multipart/form-data"
。这是一个如何更新ImageField:
首先update_form.html:
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Update</button>
</form>
然后填写表格:
from django.contrib.auth import get_user_model
class EditProfile(UserChangeForm):
class Meta:
model = get_user_model()
fields = ('email', 'name', 'avatar')
最后是视图:
def user_edit(request):
if request.method == 'POST':
form = EditProfile(request.POST, instance=request.user)
if form.is_valid():
form.save()
if request.FILES.get('avatar', None) != None:
try:
os.remove(request.user.avatar.url)
except Exception as e:
print('Exception in removing old profile image: ', e)
request.user.avatar = request.FILES['avatar']
request.user.save()
return redirect('user:profile', id=request.user.id)
else:
form = EditProfile(instance=request.user)
return render(request, 'user/user-edit.html', {'form': form})