自定义djoser创建用户端点

时间:2018-03-04 12:33:06

标签: django django-models django-rest-framework

我正在使用djoser进行身份验证。我想自定义djoser的创建用户端点。我有一个用户应用程序。这是我的用户模型

from django.db import models


class User(models.Model):
    email = models.CharField(max_length=100, blank=False)
    name = models.CharField(max_length=100, blank=False)
    last_name = models.CharField(max_length=100, blank=False)
    account_address = models.CharField(max_length=30, blank=False)
    password = models.CharField(max_length=100, blank=False)

这是我的序列化器

from rest_framework import serializers
from User.models import User


class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = User
        fields = ('url', 'id', 'email', 'name', 'last_name', 'account_address', 'password')

我的User.urls.py看起来像是

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

from .views import UserViewSet

router = DefaultRouter()

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^account/', include('djoser.urls')),
]

和项目的url.py正在进行中

from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^users/', include('User.urls')),
    url(r'^advertisements', include('advertisements.urls')),
    url(r'^account', include('wallet.urls')),
]

但我无法使用自定义模型创建用户,而当我转到user / account / create时,我会看到djoser的默认创建用户视图。请告诉我哪里做错了。谢谢:))

2 个答案:

答案 0 :(得分:5)

请注意,您已将mvn package设置为AUTH_USER_MODEL模型。

只需导入Djoser用户注册序列化程序并覆盖它。

User

您还可以覆盖序列化程序中的其他内容,例如from djoser.serializers import UserCreateSerializer as BaseUserRegistrationSerializer class UserRegistrationSerializer(BaseUserRegistrationSerializer): class Meta(BaseUserRegistrationSerializer.Meta): fields = ('url', 'id', 'email', 'name', 'last_name', 'account_address', 'password', ) ,以防您想要自定义它。

并在settings.py

create and update methods

答案 1 :(得分:1)

对我来说,我想编写一个自定义的创建方法,当我覆盖 user_create_password_retype 并使用我的方法时它起作用了,因为这是在内部使用 djoser 的 UserCreateSerializer

DJOSER = {
      ...
    "SERIALIZERS": {
        "user_create": "account.serializers.user_serializer.CustomUserCreateSerializer",
        "user": "account.serializers.user_serializer.CustomUserSerializer",
        "user_create_password_retype": "account.serializers.user_serializer.UserCreatePasswordRetypeSerializer",
    }
      ...
}

其他设置 - AUTH_USER_MODEL 到您的自定义用户模型。