老师,我的头像保存不了
来源:13-2 通过django的modelform处理头像修改
慕粉8389330
2019-09-24
html部分
form部分
class UploadImageForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = [‘head_image’]
model部分
class UserProfile(AbstractUser):
nick_name = models.CharField(max_length=40, verbose_name=‘昵称’, default=’’)
birthday = models.DateField(verbose_name=‘生日’, null=True, blank=True)
gender = models.CharField(verbose_name=‘性别’, choices=GENDER_CHOICES, max_length=6)
address = models.CharField(max_length=100, verbose_name=‘地址’, default=’’)
mobile = models.CharField(max_length=11, verbose_name=‘电话’)
head_image = models.ImageField(upload_to=‘head_image/%Y/%m’, default=‘default.jpg’)
view部分
class UploadImageView(LoginRequiredMixin, View):
login_url = '/login/'
def post(self, request, *args, **kwargs):
image_form = UploadImageForm(request.POST, request.FILES, instance=request.user)
if image_form.is_valid():
image_form.save()
return JsonResponse({
‘status’: ‘success’
})
else:
return JsonResponse({
‘status’: ‘fail’
})
2回答
-
bobby
2019-09-26
你有没有通过f12看看网络请求有没有问题?
042021-06-17 -
慕粉8389330
提问者
2019-09-24
html
<form class="clearfix" id="jsAvatarForm" enctype="multipart/form-data" autocomplete="off" method="post" action="{% url 'users:image' %}" target='frameFile'>
{% csrf_token %}
<label class="changearea" for="avatarUp">
<span id="avatardiv" class="pic">
<img width="100" height="100" class="js-img-show" id="avatarShow" src="{{ user.head_image.url }}"/>
</span>
<span class="fl upload-inp-box" style="margin-left:70px;">
<span class="button btn-green btn-w100" id="jsAvatarBtn">修改头像</span>
<input type="file" name="image" id="avatarUp" class="js-img-up"/>
</span>
</label>
</form>012021-06-17
相似问题