Search code examples
djangodjango-rest-frameworkdjango-authentication

How to customize the JSON data returned by rest-auth/user


I'm using rest_auth and rest_framework.

When I visit URL http://localhost:8080/rest-auth/user/ GET I get the following JSON data

{
    "username": "latest",
    "email": "latest@gmail.com",
    "first_name": "some first name",
    "last_name": "some last name"
}

Question

What do I need to do in order to customize the JSON data returned? I don't want it to return first_name and last_name?

Tried

I tried creating file called serializers.py and added the following to it but it isn't having any effect.

from rest_framework import serializers
from .models import *
import re

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'email')

My urls.py contains the following

url(r'^$', TemplateView.as_view(template_name="home.html"), name='home'),
url(r'^signup/$', TemplateView.as_view(template_name="signup.html"),
    name='signup'),
url(r'^email-verification/$',
    TemplateView.as_view(template_name="email_verification.html"),
    name='email-verification'),
url(r'^login/$', TemplateView.as_view(template_name="login.html"),
    name='login'),
url(r'^password-reset/$',
    TemplateView.as_view(template_name="password_reset.html"),
    name='password-reset'),
url(r'^password-reset/confirm/$',
    TemplateView.as_view(template_name="password_reset_confirm.html"),
    name='password-reset-confirm'),
#
url(r'^user-details/$',
    TemplateView.as_view(template_name="user_details.html"),
    name='user-details'),
url(r'^password-change/$',
    TemplateView.as_view(template_name="password_change.html"),
    name='password-change'),


# this url is used to generate email content
url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
    TemplateView.as_view(template_name="password_reset_confirm.html"),
    name='password_reset_confirm'),

url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
url(r'^account/', include('allauth.urls')),
url(r'^admin/', include(admin.site.urls)),

Solution

  • You can use exclude in your serializer:

    class UserSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
            exclude = ('first_name', 'last_name')