[PYTHON] Automatically write admin.py using the django-extensions admin_generator command

Thing you want to do

If there are a lot of tables, it is difficult to write in admin.py. I want you to do it automatically.

You can do this automatically by using the ʻadmin_generator command in a library called django-extensions`. It does a good job according to the contents of models.py.

What are django-extensions?

django-extensions extends the functionality of manage.py, and there are many other commands.

Installation

Install

$ pip install django-extensions

Just add to settings.py

pj_name/settings.py


.
.
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'django_extensions', # <-Postscript
]
.
.

Run

Overwrite the output result in admin.py.

$ APP contains the application name created by $ python manage.py startapp xxx.

$ python manage.py admin_generator $APP > $APP/admin.py

result

For example, this class

models.py


...
class Users(models.Model):
    user_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    first_name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    created_at = models.DateTimeField()
    updated_at = models.DateTimeField()
    del_flg = models.IntegerField()

    class Meta:
        managed = False
        db_table = 'users'
...

Like this

admin.py


...
@admin.register(Users)
class UsersAdmin(admin.ModelAdmin):
    list_display = (
        'id',
        'user_name',
        'last_name',
        'first_name',
        'email',
        'created_at',
        'updated_at',
        'del_flg',
    )
    list_filter = ('created_at', 'updated_at')
    date_hierarchy = 'created_at'
...

Create a user to log in to the management screen

$ python manage.py createsuperuser

Username (leave blank to use 'anata_no_home_dir'): <-Any name
Email address: <-Any email address
Password: <-password
Password (again):  <-again
Superuser created successfully.

Start local server

$ python manage.py runserver

Access here http://127.0.0.1:8000/admin/ スクリーンショット 2020-08-21 13 21 13

It is OK if the login-> table is displayed with the user information created earlier.

The end

Thank you for reading until the end.

Recommended Posts

Automatically write admin.py using the django-extensions admin_generator command
How to write a GUI using the maya command
Clone using the dd command
Using cgo with the go command
Execute the COPY command using python's Psycopg
Write a TCP server using the SocketServer module
Syntax highlighting on the command line using Pygments
Operate Route53 on the command line using AWS-CLI.
Write data to KINTONE using the Python requests module
I want to automate ssh using the expect command!