0

我对 Djoser 有点陌生,我想要做的是当经过身份验证的用户导航到它返回的users/meAPI 端点时,它会返回用户 ID 电子邮件和名称。我希望它也返回自定义信息我该怎么做?

4

2 回答 2

1

虽然这可能只能回答您问题的一半,但如果您使用自定义用户,那么您将添加 REQUIRED_FIELDS = ['field_you_want_included']

例如,这就是我的自定义用户配置文件之一的样子。

class CustomUser(AbstractUser):
    username = None
    user_id = models.UUIDField(default=uuid4, primary_key=True, editable=False)
    email = models.EmailField(_('email address'), unique=True)
    receive_news = models.BooleanField(null=True, blank=True, default=False)
    birth_date = models.DateField(null=True, blank=True)
    is_premium = models.BooleanField(default=True)

    USERNAME_FIELD = 'email'
    # FIELDS HERE WILL BE ADDED TO USERS/ME ENDPOINT
    REQUIRED_FIELDS = ['is_premium']
    objects = UserAccountManager()

有很多关于使用 djoser 制作自定义用户的信息,所以这里重要的是 required_fields 列表。现在,当访问用户/我时,它还将包括“is_premium”。但是,对于更复杂的包含,我会尝试覆盖视图和序列化程序。我自己没有尝试过,但如果我这样做了,我会编辑这篇文章。

于 2021-07-28T17:38:02.260 回答
0

Djoser 只是一个 Django 应用程序。只需用您自己的类覆盖 Djoser 的类,并将您的 auth URL 指向那些而不是包的那些。我不得不这样做,这是我所做的示例。

from djoser.views import TokenDestroyView as DjoserTokenDestroyView
from djoser.views import UserViewSet

class CustomUserViewSet(UserViewSet):
    """
    Overriding djoser's Users view
    """

    @extend_schema(summary="Me", responses={200: LoginSerializer, 404: UserNotFoundResponse, 401: FailedLogin})
    @action(["get", "put"], detail=False)
    def me(self, request, *args, **kwargs):
        """
        get the current User's data and KPIs settings
        """
        if request.method == MethodsNames.GET.upper():
            user = User.objects.filter(email=self.get_instance()).select_related(ACCOUNT).prefetch_related(
                RelatedNames.AUTH_TOKEN,
                'account__bundles', 'account__bundles__bundle_kpis',
                RelatedNames.USER_SELECTED_KPIS)[0]
            user_data = LoginSerializer(user, many=False)
            return Response(user_data.data)
       # some more overriding here...

然后我的 urls 文件看起来像:

from django.conf.urls import url
from django.urls import include, path
from rest_framework.routers import DefaultRouter

from users.views import TokenCreateView, CustomUserViewSet, TokenDestroyView

users = DefaultRouter()
users.register("users", CustomUserViewSet, basename='users')

login = DefaultRouter()
login.register('token', TokenCreateView, basename='login')

urlpatterns = [
    path('', include(login.urls)),
    path('', include(users.urls)),
    url(r"^token/logout/?$", TokenDestroyView.as_view(), name="logout"),
]

而不是(来自 Djoser 文档):

urlpatterns = [
    (...),
    url(r'^auth/', include('djoser.urls')),
]
于 2021-03-20T13:06:20.883 回答