pip install djangorestframework

 

# mysite/multimedia/serializers.py.

from .models import Post
from rest_framework import serializers

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = (
            'post_id', 
            'title', 
            'slug', 
            'content', 
            'featured_image', 
            'is_published',
            'is_featured',
            'created_at',
            'video',
            'category',
            'tag',
            'author',
        )

 

# mysite/multimedia/views.py

import json
from django.shortcuts import render

from rest_framework import viewsets
from rest_framework import permissions
from .serializers import PostSerializer

from .models import Post
from .config import Config

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all().filter(is_published='yes')
    serializer_class = PostSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]


def index(request):
    posts = Post.objects.all().filter(is_published='yes')

    Config.context['page_title'] = 'ទំព័រ​ដើម'
    Config.context['posts'] = posts
    Config.context['route'] = ''
    
    return render(request, 'base.html', Config.context)

def post(request, post_id):
    post = Post.objects.get(post_id=post_id)
    
    if post.video.values():
        result = post.video.values()      
        videos = [entry for entry in result]

        for entry in videos:
            entry.pop("created_at")

        videos = json.dumps(videos)
        Config.context['videos'] = videos
    else:
        Config.context['videos'] = False
    
    Config.context['page_title'] = 'ទំព័រ​​​​​​​​អត្ថបទ'
    Config.context['post'] = post
    Config.context['route'] = 'post'

    return render(request, 'base.html', Config.context)

 

# mysite/multimedia/urls.py

from django.urls import path, include

from . import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register('posts', views.PostViewSet)

urlpatterns = [
    path('', views.index, name='index'),
    path('post/<post_id>', views.post, name='post'),
    path('api/', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

 

GitHub: https://github.com/Sokhavuth/django_multimedia

Vercel: https://khmerweb-mdjango.vercel.app/api/posts