Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize the djoser create user endpoint

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

like image 791
Shoaib Iqbal Avatar asked Mar 04 '18 12:03

Shoaib Iqbal


1 Answers

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'
    }
    ...
}
like image 200
Adil Malik Avatar answered Sep 21 '22 12:09

Adil Malik