Search Here

Django Rest Framework API Serializer Tips Make field hidden in Serializer Response

In Django Rest Framework if you want to hide a field from sending as a response returned from Django Server then configure in your serializer by adding extra_kwargs attribute within serializer.

Register App

In src\

from django.urls import path, reverse

urlpatterns = [
    path('api/users/', include('users.api_urls') ),

Create a route to access URL route within App

In users\

from django.urls import path
from users import api_views
app_name = "api_users"

urlpatterns = [
path( '', api_views.ListView.as_view(), name="list" )

Creating Serializer

In users\

from rest_framework import serializers
from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {
            'password' : {
                'write_only' : True

To make a field hidden use extra_kwargs which takes a dictionary and specify the field as key and pass write_only as True to make the field hidden during fetching response.
The attribute write_only make field writable but cannot read from the response.

Creating Views

In users\

from rest_framework.response import Response
from rest_framework.views import APIView
from django.contrib.auth.models import User

from users.serializers import UserSerializer

# Create your views here.
class ListView( APIView ):

    def get(self, request, format=None):
        info = {
            'list': []

        query_set = User.objects.all()
        serializer = UserSerializer( query_set, many=True )
        info['list'] =

        return Response(info)

Import UserSerializer and to pass the response call the .data an attribute which generates the JSON response.

Watch Video