django项目中如何通过modelform处理头像修改

1. models.py代码

from django.contrib.auth.models import AbstractUser


class UserProfile(AbstractUser):
    gender_choices = (
        ("male", "男"),
        ("female", "女"),
    )
    nick_name = models.CharField(max_length=50, verbose_name="昵称", default="")
    birthday = models.DateField(verbose_name="生日", blank=True, null=True)
    gender = models.CharField(max_length=6, choices=gender_choices, verbose_name="性别")
    address = models.CharField(max_length=100, verbose_name="地址", default="")
    mobile = models.CharField(max_length=11, verbose_name="手机号")
    image = models.ImageField(upload_to="head_image/%Y/%m", default="default.jpg", verbose_name="用户头像")

    class Meta:
        # 修改表在后台显示名称
        verbose_name = "用户信息"
        verbose_name_plural = verbose_name

    def __str__(self):
        if self.nick_name:
            return self.nick_name
        else:
            return self.username

2. forms.py代码

from django import forms

from apps.users.models import UserProfile


class UploadImageForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ["image"]

3. views.py代码

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.base import View

from apps.users.forms import UploadImageForm


class UploadImageView(LoginRequiredMixin, View):
    """修改用户头像"""
    def post(self, request):
        # 处理用户上传的头像, 注意此处的三个参数,非常的重要
        upload_image_form = UploadImageForm(data=request.POST, files=request.FILES, instance=request.user)
        if upload_image_form.is_valid():
            upload_image_form.save()
            return JsonResponse({"status": "success"})
        else:
            return JsonResponse({"status": "fail"})

4. urls.py代码

from django.urls import path
from . import views


urlpatterns = [
    path("upload_image/", views.UploadImageView.as_view(), name="upload_image"),  # 修改用户头像
]

猜你喜欢

转载自blog.csdn.net/weixin_42289273/article/details/114841581