- 用户头像是一个ImageField,需要借助forms.ModelForm来实现
image = models.ImageField(upload_to="image/%Y/%m", default=u"image/default.png", max_length=100)
- 定义ModelForm
class UploadImageForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ["image"]
- 编写url
url(r'^image/upload/$', UploadImageView.as_view(), name="image_upload"),
-
编写view 方法1
- 这里需要注意的是用户的头像是保存在 request.FILES中的
class UploadImageView(LoginRequiredMixin, View):
"""
用户修改头像
"""
def post(self, request):
image_form = UploadImageForm(request.POST, request.FILES)
if image_form.is_valid():
image = image_form.cleaned_data["image"]
request.user.image = image
request.user.save()
return HttpResponse("{'status':'success'}", content_type='application/json')
- 编写view 方法2
class UploadImageView(LoginRequiredMixin, View):
"""
用户修改头像
"""
def post(self, request):
image_form = UploadImageForm(request.POST, request.FILES, instance=request.user)
if image_form.is_valid():
image_form.save()
return HttpResponse("{'status':'success'}", content_type='application/json')
- 编写html
这里需要注意 enctype字段的值
<form class="clearfix" id="jsAvatarForm" enctype="multipart/form-data" autocomplete="off" method="post" action="{% url "users:image_upload" %}" target='frameFile'>
<label class="changearea" for="avatarUp">
<span id="avatardiv" class="pic">
<img width="100" height="100" class="js-img-show" id="avatarShow" src="{{ MEDIA_URL }}{{ request.user.image }}"/>
</span>
<span class="fl upload-inp-box" style="margin-left:70px;">
<span class="button btn-green btn-w100" id="jsAvatarBtn">修改头像</span>
{# type="file" name="image" 必须这样写 #}
<input type="file" name="image" id="avatarUp" class="js-img-up"/>
</span>
</label>
{% csrf_token %}
</form>
网友评论