React-admin and django rest framework

Having recently stumbled upon an article about react-admin , I decided to try what kind of beast it is. It was interesting to tie this to the jung, fortunately there is a dataprovider for the rest framework .



But first you need to submit the admin panel as an api. In principle, this is easily done with the help of view sets, which can be generated automatically by going through the models from the admin panel.



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 the differentiation of rights works out of the box!







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











I would like to make them closer to the model 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 statics for the front, I made 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, just add 'django_react_admin' to INSTALLED_APPS and add 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 itself on GitHub



Generally admin panel in the form of api is very useful. You can, for example, make a mobile application on nativescript.



All Articles