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.
django-extensions extends the functionality of manage.py, and there are many other commands.
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
]
.
.
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
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'
...
$ 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/

It is OK if the login-> table is displayed with the user information created earlier.
Thank you for reading until the end.
Recommended Posts