Skip to main content

A Django app to easily integrate with React from models.

Project description

DRF And React By Schema - Django

This package, with the corresponding npm package with the same name, enables a django headless infrastructure for running with react very easily, directly from your models.

About:

React has great power in building highly responsive and dynamic interfaces for users, with great flexibility and quality.

On the other hand, Django offers a consolidated infrastructure, high performance, and a popular way to organize data models for creating, removing, and updating data (CRUD) for simple to highly complex and intricate systems.

A recognized and active library in Django, called Django Rest Framework, or simply DRF, leverages these Django characteristics to allow developers to create powerful API schemas directly related to the data model, using the concept of viewsets (analogous to views) and serializers (analogous to forms).

Building systems with a large number of forms for managing different processes is Django’s power, but its approach to the interface, based on views, forms, and especially templates, templatetags, and inclusiontags, is outdated, as every update must refresh the entire page, following a logic of HTML template rendering.

An attractive option is to use React as the client (interface) for a Django instance with DRF as the server. In other words, Django serves the data and performs operations on the data as a Headless server (i.e., without views, forms, or templates, but only through the API).

However, a common problem with this approach is that it often requires duplicating work in the client (React) and the server (Django/DRF) to handle form interactions and validations in React that are related to the server models.

As an example, let’s suppose that you want to manage products. Let’s say that each product belongs to a product category. Let’s assume we have the categories “fruits and vegetables” and “grains,” and the products lettuce, papaya, and grapes in the “fruits and vegetables” category, and beans, rice, and fava beans in the “grains” category. In this example, we could consider that each product has attributes such as “name”, “description”, “unit”, “price per unit,” and “availability”. For the categories, we could say they have attributes like “name” and “description”.

In Django, the data model is created very simply: create a ProductCategory and a Product models, with a “ForeignKey” relationship indicating a one-to-many relationship between the product and the category (one category can have many products, and one product belongs to a single category).

In React, you would need to build the form, types of components (simple text input, long text input, numeric input, password input, yes/no switch input, autocomplete multiple-choice, single-choice dropdown, date pickers, etc.), validation conditions (whether it’s mandatory or not, initial data, data format masks, etc.).

The problem is that this is redundant work because this information is already available in the Django model!

But how do you pass the data structure information to React? This is where DRF and React By Schema - Django (drf-react-by-schema-django) comes in. It creates a powerful schema on the server that can be accessed by React via the OPTION method.

And how do you build forms, validation conditions, and form components in React? This is where DRF and React By Schema - React (drf-react-by-schema-react) comes in, which consumes the schemas generated by drf-react-by-schema-django and automatically builds all of this for the developer with very few lines of code, while allowing complete customization of the interfaces (layout).

Furthermore, on the Django side, drf-react-by-schema-django automatically generates a full API endpoint structure directly from the app’s models, along with powerful search tools, filters, nested related objects, validation, and handling of object creation, updating, and removal processes, which is a challenging task to do manually in Django DRF because it typically requires in-depth knowledge of serializers and viewsets. The Django package simplifies this entire process for the developer while maintaining performance.

On the React side, drf-react-by-schema-react offers a range of powerful components that allow for the automatic construction of forms, including forms for multiple related objects (through editable tables), using the full power of MUI and MUI x-DataGrid.

The DRF and React By Schema Suite is available for React at https://www.npmjs.com/package/drf-react-by-schema and for Django at https://pypi.org/project/drf-react-by-schema/.

Pre-requisites:

  • django-rest-framework

  • drf-nested-routers

  • django-cors-headers

  • djangorestframework-simplejwt

  • django-filter

Quick start:

  1. Add and configure the pre-requisite apps

  2. Add “drf-react-by-schema” to your INSTALLED_APPS setting like this:

    INSTALLED_APPS = [
        ...
        'drf_react_by_schema',
    ]
  3. Configure Django Rest Framework in settings, adding the drf-react-by-schema rederer, metadata and filter backend, as in the example below:

    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
        ),
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework_simplejwt.authentication.JWTAuthentication',
            'rest_framework.authentication.SessionAuthentication',
        ),
        "DEFAULT_RENDERER_CLASSES": [
            "rest_framework.renderers.JSONRenderer",
            "drf_react_by_schema.renderers.CustomBrowsableAPIRenderer",
        ],
        'DEFAULT_METADATA_CLASS': 'drf_react_by_schema.metadata.Metadata',
        'DEFAULT_FILTER_BACKENDS': [
            'rest_framework.filters.SearchFilter',
            'drf_react_by_schema.filters.DRFReactBySchemaOrderingFilter',
        ],
    }
  4. Configure drf-react-by-schema, for example adding the apps that should be condered for building the API endpoints. If not added to settings, the default will be [‘main’]. Example:

    DRF_REACT_BY_SCHEMA = {
        'APPS': [
            'main',
        ],
        'PAGINATION_MODE': 'server',
    }
  5. Include the URL configuration in your project urls.py like this:

    urlpatterns = [
        ...
        path('', include('drf_react_by_schema.urls')),
    ]
  6. Start the development server and visit http://127.0.0.1:8000/api/endpoints and you will see all endpoints available.

  7. Create or include your React app, for example in a frontend folder. You can find a quick guide on how to install the DRF And React By Schema - React package in your React app at https://www.npmjs.com/package/drf-react-by-schema .

You can customize viewsets and serializers to annotate other attributes.

This package offers special fields for added control over metadata directly from model.

For any questions, please add issues in the gitlab repository.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

drf-react-by-schema-0.10.6.tar.gz (30.2 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page