[PYTHON] ng-admin + Django REST framework ready-to-create administration tool

I tried to make an administration tool with Django REST framework and ng-admin

Ng-admin and Django REST framework as ways to implement management tools with REST API + Static web I tried using -framework.org/). This article is intended for readers with experience with Python and Javascript. The source code of this article is published in the following repositories.

Library introduction

--Django REST framework: A Python web framework that makes it easy to create REST APIs. As the name implies, it's based on Django. --ng-admin: Javascript client library specialized for administrative tools. This depends on Angularjs.

Server configuration

Needless to say in the figure, the server configuration is as follows.

---------------------------
Static Web (127.0.0.1:8080) // ng-admin
---------------------------
           |
---------------------------
Web API    (127.0.0.1:8000) // REST framework
---------------------------

Environment

It is assumed that Python 3.5.2 is installed by Pyenv (pyenv-virtualenv). Also assume that you have npm installed. By the way, my environment is macOS El Capitan.

Django REST framework

Install the Django REST framework. This time, I will use the repository prepared by the author.

  1. Get the repository git clone https://github.com/algas/rest-admin-example.git
  2. Creating a virtualenv environment cd rest-admin-example && pyenv virtualenv 3.5.2 rest-admin-example
  3. activate virtualenv pyenv activate rest-admin-example
  4. Install dependent libraries pip install -U pip && pip install -r requirements.txt
  5. database migration
    cd tutorial && python manage.py migrate
  6. Create a new superuser python manage.py createsuperuser
    Follow the guide to enter your username, email address and password.

If you want to create your own environment from scratch, please refer to the quickstart tutorial. We are doing the same as this tutorial except for some bug fixes.

ng-admin

  1. Move the current directory cd ../js
  2. Install dependent libraries npm install ng-admin --save

Be sure to run the above npm install in the js directory. It depends on the path to the created node_modules.

Start the server

Prepare a two-screen terminal to launch the Django server and the (Static) web server separately.

Django REST framework

  1. Move the current directory cd /path/to/rest-admin-example/tutorial
  2. Start the server python manage.py runserver
  3. Operation check Access the following with a browser. http://127.0.0.1:8000/

ng-admin

Here we use the python 3 standard web server (http.server). Other web servers such as nginx are fine.

  1. Move the current directory cd /path/to/rest-admin-example/js
  2. Start the server python -m http.server 8080
  3. Operation check Access the following with a browser. http://127.0.0.1:8000/

Code commentary

API

Two API groups, users and groups, are defined. The definition of each model is as follows.

User: url, username, email, groups Group: url, name

Users can belong to any number of groups. url represents a link to the created API element. http://127.0.0.1:8000/users/1/ http://127.0.0.1:8000/groups/1/

Management page

On the management page, the function to display the list of User and Group and create new elements has been implemented. This feature is implemented in two files, index.html and admin.js.

index.html


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Rest Admin Page</title>
        <link rel="stylesheet" href="node_modules/ng-admin/build/ng-admin.min.css">
    </head>
    <body ng-app="restAdmin">
        <div ui-view></div>
        <script src="node_modules/ng-admin/build/ng-admin.min.js" type="text/javascript"></script>
        <script src="admin.js" type="text/javascript"></script>
    </body>
</html>

The above refers to admin.js below, in addition to js and css of ng-admin installed on node_modules.

admin.js


var restAdmin = angular.module('restAdmin', ['ng-admin']);
restAdmin.config(['NgAdminConfigurationProvider', function (nga) {
    var admin = nga.application('Rest Admin')
      .baseApiUrl('http://127.0.0.1:8000/');

    var group = nga.entity('groups').identifier(nga.field('url')).url(function(entityName, viewType, identifierValue, identifierName) {
        return 'groups/';
    });
    var groupFields = [
        nga.field('url'),
        nga.field('name')
    ]
    group.listView().fields(groupFields);
    group.creationView().fields(groupFields);
    admin.addEntity(group);

    var user = nga.entity('users').identifier(nga.field('url')).url(function(entityName, viewType, identifierValue, identifierName) {
        return 'users/';
    });
    var userFields = [
        nga.field('url'),
        nga.field('username'),
        nga.field('email'),
        nga.field('groups', 'json'),
    ]
    user.listView().fields(userFields);
    user.creationView().fields(userFields);
    admin.addEntity(user);

    nga.configure(admin);
}]);

First, we define http://127.0.0.1:8000/ as baseApiUrl. Next, define users and groups as Entity. The default specification for ng-admin assumes that the URI does not end with a slash (/). However, the django framework spec always puts a slash (/) at the end of the URI, so I'm defining a url function to absorb this difference. ListView and creationView are defined for users and groups respectively. Since the element of groups in User is defined by Array, json is specified as Field Type of ng-admin.

important point

--CORS settings Under normal settings, the API cannot pass JSON to ng-admin due to a Cross-Origin Resource Sharing issue. I'm working around this issue by using django_cors_middleware. Since it is set in settings.py, no special action is required when referencing the author's repository. --Dependency resolution The fork source of the above library wasn't updated and wasn't compatible with Django-1.10, so I've solved it by referring to the branch of the user who did Pull Req. This is also described in requirements.txt, so you should be able to avoid the problem.

Miscellaneous feelings

Since the Django REST framework itself provides a web UI, the benefits of combining it with ng-admin may be hard to see. The Django REST framework is also useful on its own. Of course, ng-admin can also work with other web APIs.

Recommended Posts

ng-admin + Django REST framework ready-to-create administration tool
Django REST framework basics
Django Rest Framework Tips
Django REST framework stumbling block
Django REST framework with Vue.js
Login with django rest framework
[Django] Use MessagePack with Django REST framework
Logical deletion in Django, DRF (Django REST Framework)
Understand the benefits of the Django Rest Framework
CRUD GET with Nuxt & Django REST Framework ②
Miscellaneous notes about the Django REST framework
CRUD POST with Nuxt & Django REST Framework
CRUD GET with Nuxt & Django REST Framework ①
Django REST Framework + Clean Architecture Design Consideration
Django REST framework A little useful to know.
Implement JWT login functionality in Django REST framework
Implementing authentication in Django REST Framework with djoser
Create a Todo app with Django REST Framework + Angular
More new user authentication methods with Django REST Framework
Create a Todo app with the Django REST framework
Create APIs around user authentication with Django REST Framework
When you want to filter with Django REST framework
List method for nested resources in Django REST framework
Implement APIs at explosive speed using Django REST Framework
[Django Rest Framework] Customize the filter function using Django-Filter
Implement hierarchical URLs with drf-nested-routers in Django REST framework
Django python web framework
How to write custom validations in the Django REST Framework
How to reset password via API using Django rest framework
Django rest framework decorators ʻaction decorator replaces list_route and detail_route`