DRF ImageField不一致的行为

时间:2019-05-30 17:59:45

标签: python django rest api django-rest-framework

我正在使用DRF创建Django API。我有一个这样的自定义用户模型:

models.py:

from typing import Type, List
from uuid import uuid4
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.models import TimeStampedModel

from main.apps.user.managers import UserManager


def to_profile_picture(instance: "User", filename: str) -> str:
    return f"profile_pictures/{instance.email}/{uuid4()}_{filename}"


class User(AbstractBaseUser, TimeStampedModel, PermissionsMixin):
    email = models.EmailField(_("Email Address"), unique=True)
    first_name = models.CharField(
        _("First Name"), max_length=128, blank=True, null=True
    )
    last_name = models.CharField(_("Last Name"), max_length=128, blank=True, null=True)
    display_name = models.CharField(_("Display Name"), max_length=128)
    is_active = models.BooleanField(_("Active"), default=True)
    is_staff = models.BooleanField(_("Is staff"), default=False)
    profile_picture = models.ImageField(
        upload_to=to_profile_picture, null=True, blank=True
    )

    objects: Type[UserManager] = UserManager()

    USERNAME_FIELD: str = "email"
    REQUIRED_FIELDS: List[str] = []

    class Meta:
        verbose_name: str = _("User")
        verbose_name_plural: str = _("Users")

    @property
    def get_full_name(self) -> str:
        return f"{self.first_name} {self.last_name}"

managers.py:

from django.contrib.auth.base_user import BaseUserManager


class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError("The given email must be set")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email: str, password: str = None, **extra_fields):
        extra_fields.setdefault("is_superuser", False)
        extra_fields.setdefault("is_staff", False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault("is_superuser", True)
        extra_fields.setdefault("is_staff", True)

        if extra_fields.get("is_superuser") is not True:
            raise ValueError("Superuser must have is_superuser=True.")

        return self._create_user(email, password, **extra_fields)

viewsets.py:

from typing import Type
from rest_framework import viewsets, status
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.decorators import action

from main.apps.user.models import User
from main.apps.user.serializers import UserSerializer


class UsersViewset(viewsets.ModelViewSet):
    def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.action == "create":
            permission_classes = [AllowAny]
        else:
            permission_classes = [IsAuthenticated]
        return [permission() for permission in permission_classes]

    queryset = User.objects.all()
    serializer_class: Type[UserSerializer] = UserSerializer

    def create(self, request, *args, **kwargs):
        serializer: UserSerializer = UserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = User.objects.create_user(
            serializer.validated_data.pop("email"),
            serializer.validated_data.pop("password"),
            **serializer.validated_data,
        )
        return Response(status=status.HTTP_201_CREATED, data=UserSerializer(user).data)

    @action(detail=False)
    def me(self, request: Request):
        return Response(
            status=status.HTTP_200_OK, data=UserSerializer(request.user).data
        )

serializers.py:

from typing import Type, Tuple, Dict, Any

from rest_framework import serializers

from main.apps.user.models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model: Type[User] = User
        fields: Tuple[str] = (
            "id",
            "email",
            "password",
            "display_name",
            "first_name",
            "last_name",
            "profile_picture",
        )
        extra_kwargs: Dict[str, Any] = {"password": {"write_only": True}}

这里的问题是,当我转到为UserViewset定义的路由并触发list操作时,它将返回文件前面带有http://domain/的完整URL。路径,实际上正是我想要的。但是在/me路由或create路由上,仅返回路径,没有域。

我认为这可能与上下文有关,该上下文未在自定义路由中传递给序列化程序,但可能在默认的ModelViewset路由中。

如果有人知道我如何在其他路线上复制列表动作行为,我会很高兴的!

1 个答案:

答案 0 :(得分:0)

好的,发现这就是我的想法,我只需要将请求作为上下文传递给我的序列化器即可。

从中更改文件me中的方法viewsets.py

@action(detail=False)
    def me(self, request: Request):
        return Response(
            status=status.HTTP_200_OK, data=UserSerializer(request.user).data
        )

对此:

@action(detail=False)
    def me(self, request: Request):
        return Response(
            status=status.HTTP_200_OK,
            data=UserSerializer(request.user, context={"request": request}).data,
        )