My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Post hidden from Hashnode

Posts can be hidden from Hashnode network for various reasons. Contact the moderators for more details.

React-admin and Django Rest Framework

Eddie Svirsky's photo
Eddie Svirsky
·Dec 11, 2019

[Translation of an article originally posted on habr.ru , published by pawnhearts on December 5, 2019]

Having recently stumbled upon an article about react-admin, I decided to try and see what kind of beast it is. It was interesting to attach it to Django, fortunately there was a data provider for the Rest Framework .

But first you need to present the admin in the form of an API. In theory, this is easily done with the help of viewsets, which can be generated automatically by going through the models in admin.

def get_serializer_class(model):
     return type(
         f"{model.name}Serializer",
         (ModelSerializer,),
         {"Meta": type("Meta", (), {"model": model, "fields": "all"})},
     )
for model, model_admin in admin.site._registry.items():
  params = {
         "queryset": model.objects.all(),
         "filter_backends": [DjangoFilterBackend, OrderingFilter],
         "info": action(methods=["get"], detail=False)(get_info(model_admin)),
         "serializer_class": get_serializer_class(model),
         "basename": model._meta.model_name,
         "request": r,
         "fields": list(model_admin.get_fields(r)),
         "list_display": list(model_admin.get_list_display(r)),
         "ordering_fields": list(model_admin.get_sortable_by(r)),
         "filterset_fields": list(model_admin.get_list_filter(r)),
         "permission_classes": [permissions.IsAdminUser, permissions.DjangoModelPermissions],
         "pagination_class": CustomPageNumberPagination
     }
     viewset = type(f"{model.name}ViewSet", (viewsets.ModelViewSet,), params)
     router.register(
         f"{model._meta.app_label}/{model._meta.model_name}", viewset
     )

Even separation of privileges worked out of the box!

Django rest framework

React-admin works pretty much out of the box. Thanks to ListGuesser, EditGuesser, etc forms are created automatically.

Auth user

Auth user password

Wanted to make them closer to the models based on data from drf options, but I couldn’t figure it out right away, I left the task for later (pull requests are welcome).

To make it convenient to collect statistics for the frontend, I created a small management command:

import subprocess, os, sys

from django.core.management.base import BaseCommand
from django.core import management

class Command(BaseCommand):
    help = 'Build react-admin'

    def handle(self, *args, **options):
        cwd = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../src')
        ps = subprocess.Popen("yarn install", shell=True, cwd=cwd)
        ps.wait() and sys.exit(1)
        ps = subprocess.Popen("yarn build", shell=True, cwd=cwd)
        ps.wait() and sys.exit(1)
        management.call_command('collectstatic')

To try it, you just need to add ‘django_react_admin’ to INSTALLED_APPS and add these urls:

from django_react_admin import urls
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('react_admin/', include(urls.urlpatterns)),
]

The project is on Github

In general, admin in the form of API is very useful. It’s possible, for example, to create a mobile application in NativeScript.