mincom
mincom

Reputation: 979

Allow HTML characters in Django Rest Framework serializers

I am returning HTML text from Django Rest Framework, but special characters are rewritten as "HTML safe" text.

How do I prevent this behaviour? I know there is a mark_safe() function in Django, but that would require me to rewrite the serializer. Is there an easy way to do this offered by DRF?

Here is my serializer:

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ("html_text",)

Note that the text is safe and only input by admins, not by end users.

Upvotes: 2

Views: 1341

Answers (1)

Andrew
Andrew

Reputation: 8674

DRF does not do this out of the box.

Either your frontend or some other code is doing this for you. This escaping is automatic for all the modern UI frameworks that I know of. I'm not a frontend dev so maybe I missed one.

To demonstrate this I took just a few minutes created an empty project with one model and used the default routers, sqlite, etc. This is fairly straighforward to do.

Package               Version
--------------------- -------
Django                3.2.4
djangorestframework   3.12.4
~/htm ❯ http post :8000/page/ \
        html_string="<script>window.alert()</script>" \
        html_text="<script>console.log('hi')</script>"
{
    "html_string": "<script>window.alert()</script>",
    "html_text": "<script>console.log('hi')</script>",
    "id": 1
}

~/htm ❯ http :8000/page/1/
{
    "html_string": "<script>window.alert()</script>",
    "html_text": "<script>console.log('hi')</script>",
    "id": 1
}

And the views, routers, and models

class Page(models.Model):
    html_string = models.CharField(max_length=1024)
    html_text = models.TextField()

class PageSerializer(ModelSerializer):
    class Meta:
        model = Page
        fields = "__all__"

class PageViewSet(ModelViewSet):
    queryset = Page.objects.all()
    serializer_class = PageSerializer

Upvotes: 1

Related Questions