[PYTHON] Django tutorial summary for beginners by beginners ⑦ (Customize Admin)

Introduction

This article is a series of steps through Django's official tutorials. This time, we'll move on to the fourth article, "Creating your first Django app, part 7." This is the final episode.

Django tutorial summary for beginners by beginners ① (project creation ~) Django tutorial summary for beginners by beginners ② (Model, Admin) Django tutorial summary for beginners by beginners ③ (View) Django tutorial summary for beginners by beginners ④ (Generic View) Django tutorial summary for beginners by beginners ⑤ (test) Django tutorial summary for beginners by beginners ⑥ (static file) Summary of Django tutorials for beginners by beginners ⑦ (Customize Admin)

Creating your first Django app, part 7

https://docs.djangoproject.com/ja/3.0/intro/tutorial07/

This time, the following articles were very helpful throughout! Django Admin Reverse Lookup (Basic)

customize admin form

Summary of Django tutorials for beginners by beginners (Model, Admin) I registered the Question model with ʻadmin.site.register (Question)` and displayed the object from the Admin page.

We are currently using the default Admin page, so we will change this.

polls/admin.py


from django.contrib import admin

from .models import Question


class QuestionAdmin(admin.ModelAdmin):
    fields = ['pub_date', 'question_text']

admin.site.register(Question, QuestionAdmin)

This is a change in the order of the fields in the edit form. To edit the admin page in this way, create a class for each model and pass it to ʻadmin.site.register () `as a second argument.

You can also split the form by specifying field set as shown below.

polls/admin.py


from django.contrib import admin

from .models import Question


class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question_text']}),
        ('Date information', {'fields': ['pub_date']}),
    ]

admin.site.register(Question, QuestionAdmin)

image.png

Add relational objects

The Choices currently associated with the Question are no longer manageable. For the time being, register the model like the first Question.

from django.contrib import admin

from .models import Choice, Question
# ...
admin.site.register(Choice)

Now you can treat it like a Question.

image.png

Questions can also be selected properly. Press + to jump to the new Question page. When created there, the newly created Question will be redirected to the Create Choice page of the selected Choice. (Much high tech)

From here, let's change it so that Choice can be created at the same time when creating Quesition.

Delete ʻadmin.site.register ()` for Choice and change it as follows:

polls/admin.py


from django.contrib import admin

from .models import Choice, Question


class ChoiceInline(admin.StackedInline):
    model = Choice
    extra = 3


class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question_text']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
    ]
    inlines = [ChoiceInline]

admin.site.register(Question, QuestionAdmin)

You can work with different models by using ʻadmin.StackedInline`.

This will result in: image.png

There is also a "Add another Choice" link at the bottom of the form. This is also high tech.

You can also use TabularInline instead of StackedInline to work with other models. If you use it, it will be as follows. image.png

Customize the changelist page on the admin site

A changelist page is such a page. スクリーンショット 2020-01-06 19.25.14.png By default it is supposed to display the str of the object.

Set list_display to add another column to this list.

polls/admin.py


class QuestionAdmin(admin.ModelAdmin):
    # ...
    list_display = ('question_text', 'pub_date', 'was_published_recently')

In addition to the field names, you can also specify methods for the model as described above.

image.png This will give you a list like this.

If you press the column header (the part called QUESTION TEXT), it will be sorted accordingly. This is also high tech.

Also, the was_published_recently part is a method, so it does not correspond to this. This is fixed in polls / models.py.

polls/models.py


class Question(models.Model):
    # ...
    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

Also, set the filter / search function in this list. Use list_filter and search_fields respectively.

polls/admin.py


list_filter = ['pub_date']
search_fields = ['question_text']

Customize the look and feel of your admin site

So far, we have added the functionality of the Admin page. Next, we will change the design.

Create a templates directory in your project directory. (The directory where manage.py etc. are located)

Edit mysite / settings.py.

mysite/settings.py


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

DIRS is a list of directories on the file system that Django checks when loading templates. It's like a search path.

Find the Django admin template directory (django / contrib / admin / templates) and copy the template ʻadmin / base_site.html` to the newly created directory.

You can find the location of Django's source files with the following command:

$ python -c "import django; print(django.__path__)"

admin/base_site.html


{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>
{% endblock %}

You can override the template in this way. I changed the site header as an example, but you can use the django.contrib.admin.AdminSite.site_header attribute to do the same.

At the end

You've completed all of Django's official tutorials! Of course, there were some similarities with Rails and Phoenix, but the specifications were quite different and I enjoyed studying!

Have a good Django life!

p.s. If you find any mistakes or misinterpretations in this series, please make an edit request or softly comment ...

Recommended Posts

Django tutorial summary for beginners by beginners ⑦ (Customize Admin)
Django Tutorial Summary for Beginners by Beginners (Model, Admin)
Django tutorial summary for beginners by beginners ③ (View)
Django tutorial summary for beginners by beginners ⑤ (test)
Django tutorial summary for beginners by beginners ⑥ (static file)
Django tutorial summary for beginners by beginners ① (project creation ~)
Django tutorial summary for beginners by beginners ④ (Generic View)
Python Django tutorial summary
Reference resource summary (for beginners)
[Explanation for beginners] TensorFlow tutorial MNIST (for beginners)
Machine learning summary by Python beginners
[For beginners] Django -Development environment construction-
What is scraping? [Summary for beginners]
TensorFlow Tutorial MNIST For ML Beginners
Django Girls Tutorial Summary First Half
Pandas basics summary link for beginners
[Deprecated] Chainer v1.24.0 Tutorial for beginners
TensorFlow Tutorial -MNIST For ML Beginners
[Explanation for beginners] TensorFlow tutorial Deep MNIST
Django Summary
[Linux command summary] Command list [Must-see for beginners]
[Django] Want to customize your admin page?
Django Summary
Linux operation for beginners Basic command summary
A textbook for beginners made by Python beginners
An introduction to object-oriented programming for beginners by beginners
About Nim higher-order functions for Nim beginners written by Nim beginners
Conducting the TensorFlow MNIST For ML Beginners Tutorial
Roadmap for beginners
Python Django Tutorial (5)
Python Django Tutorial (2)
Python tutorial summary
Django 1.9 for internationalization
django tutorial memo
Python Django Tutorial (8)
Python Django Tutorial (6)
Start Django Tutorial 1
Django filter summary
Python Django Tutorial (7)
Python Django Tutorial (1)
Python Django tutorial tutorial
Python Django Tutorial (3)
Python Django Tutorial (4)
[Translation] NumPy Official Tutorial "NumPy: the absolute basics for beginners"
Python beginners try adding basic auth to Django admin
I tried the MNIST tutorial for beginners of tensorflow.
Summary of pre-processing practices for Python beginners (Pandas dataframe)
[Linux] Basics of authority setting by chmod for beginners
[For beginners] Django Frequently used commands and reference collection