Django Rest Framework Serializer Not Applying Model Field Defaults

I'm working on a simple Django project from drf documentation where I have a Snippet model that uses the pygments library to provide language and style options for code snippets. I've set default values for the language and style fields in my model, but when I try to serialize this model using Django Rest Framework (DRF), the default values don't seem to be applied while running server.

# models.py
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles

LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLES = sorted([(style, style) for style in get_all_styles()])

class Snippet(models.Model):
    title = models.CharField(max_length=50, blank=True, default="")
    linenos = models.BooleanField(default=False)
    code = models.TextField()
    language = models.CharField(choices=LANGUAGES, default="python", max_length=50)
    style = models.CharField(choices=STYLES, default="monokai", max_length=50)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["updated_at"]
#serializers.py
from rest_framework import serializers
from .models import Snippet


class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = "__all__"

    def get_initial(self):
        initial = super().get_initial() or {}
        initial["language"] = Snippet._meta.get_field("language").get_default()
        initial["style"] = Snippet._meta.get_field("style").get_default()
        print(initial)
        return initial

{'title': '', 'linenos': False, 'code': '', 'language': 'python', 'style': 'monokai'}
{'title': '', 'linenos': False, 'code': '', 'language': 'python', 'style': 'monokai'}

but when I run server the language and style choices arent set to default. here is the imageenter image description here

use the following code to pass the default value:

class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = "__all__"
        extra_kwargs = {'language': {'default': 'python'}, 'style': {'default': 'monokai'}}
Back to Top