Customize the djoser create user endpoint

亡梦爱人 提交于 2020-02-01 19:01:05

问题


I am using djoser for auth purposes. I want to customize the create user end point of djoser. I have a User app. Here is my User model

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)

and here is my serializer

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')

and my User.urls.py looks like following

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')),
]

and project's url.py is follwing

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')),
]

but i am unable to create user with customized model instead when i go to user/account/create i see djoser's default create user view. Anybody please tell where I am doing wrong. Thanks :)


回答1:


Having in mind that you have set the AUTH_USER_MODEL to your User model.

Just import the Djoser User Registration Serializer And override it.

from djoser.serializers import UserCreateSerializer as BaseUserRegistrationSerializer

class UserRegistrationSerializer(BaseUserRegistrationSerializer):
    class Meta(BaseUserRegistrationSerializer.Meta):
        fields = ('url', 'id', 'email', 'name', 'last_name', 'account_address', 'password', )

You can also override other things in the serializer like create and update methods in case if you want to customize it.

And in settings.py

DJOSER = {
    ...
    'SERIALIZERS': {
         'user_create': 'yourapp.serializer.UserRegistrationSerializer'
    }
    ...
}


来源:https://stackoverflow.com/questions/49095424/customize-the-djoser-create-user-endpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!