Convert Markdown to HTML in DRF

Posted on: May 12th 2019, 1:11:22 pm

Save the markdown in text in django models then output it as HTML in api

# models.py
class Page(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, max_length=255)
    short_description = models.CharField(max_length=255)
    # Input Markdown then render it as html
    content = models.TextField(blank=True)
    is_active = models.BooleanField(default=False)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)

class PageSerializer(serializers.ModelSerializer):
    categories = serializers.SlugRelatedField()
    banner = serializers.ImageField(max_length=None)
    content = serializers.SerializerMethodField()

    class Meta:
        model = Page
        fields = (

    def get_content(self, obj):
        '''Return the markdown content of obj as html format'''
        import markdown2

        # Enable code blocks
        content = markdown2.markdown(
        return content