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’
})