👋
Welcome to my blog!

Hide Password from Django Serializer when using Depth

Hide password or sensitive information when using Django depth functionality in Django Rest Framework Serializer.

Hide Password from Django Serializer when using Depth
Django

Published At

5/15/2021

Reading Time

~ 2 min read

There are times when you create an API with user in it and then when you wanna need more details, you set depth of the API and to the surprise you see some confidential fields in it. First in User serializer (or in serializer in which you wanna hide fields) you need to exclude those fields.

python
from django.contrib.auth import get_user_model
from rest_framework import serializers
 
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        exclude = ['password', 'last_login', 'is_superuser', 'is_staff',
                   'is_active', 'date_joined', 'groups', 'user_permissions']
python
from django.contrib.auth import get_user_model
from rest_framework import serializers
 
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        exclude = ['password', 'last_login', 'is_superuser', 'is_staff',
                   'is_active', 'date_joined', 'groups', 'user_permissions']

And when you want to include user into another serializer, instead of using PrimaryRelated or StringRelated or any other, use that serializer directly, like follows:

python
from mymasters.models.Course import Course
from mymasters.serializers.UserSerializer import UserSerializer
from rest_framework import serializers
 
class CourseSerializer(serializers.ModelSerializer):
    teacher = UserSerializer()
 
    class Meta:
        model = Course
        fields = '__all__'
        depth = 1
python
from mymasters.models.Course import Course
from mymasters.serializers.UserSerializer import UserSerializer
from rest_framework import serializers
 
class CourseSerializer(serializers.ModelSerializer):
    teacher = UserSerializer()
 
    class Meta:
        model = Course
        fields = '__all__'
        depth = 1

👻

Do you have any questions, or simply wish to contact me privately? Don't hesitate to shoot me a DM on Twitter.

Have a wonderful day.
Abhishek 🙏

Join My Exclusive Newsletter Community

Step into a world where creativity intersects with technology. By subscribing, you'll get a front-row seat to my latest musings, full-stack development resources, and exclusive previews of future posts. Each email is a crafted experience that includes:

  • In-depth looks at my covert projects and musings to ignite your imagination.
  • Handpicked frontend development resources and current explorations, aimed at expanding your developer toolkit.
  • A monthly infusion of inspiration with my personal selection of quotes, books, and music.

Embrace the confluence of words and wonder, curated thoughtfully and sent straight to your inbox.

No fluff. Just the highest caliber of ideas.