Learning history for participating in team app development in Python ~ Django Tutorial 7 ~

Introduction

This is the end of the basics of the Django tutorial. Finally, let's take a look at customizing the app's admin page. Django has a function called admin form that allows you to add, update, and delete records in a table with a browser without using SQL like phpMyAdmin in XAMPP, so we will customize it.

Basic customization

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)

Below the QuestionAdmin class is the custom content. In other words, by creating a class for each model, you can change the custom contents for each table. Specify each column name of the table created by migration with fields. At this time, they are displayed in the actual display position in order from the left. Next, let's increase the fields.



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

If you set fields to fieldsset and set (field name, {'fields': ['column name']}), you can display what information this column is. For example, ('Date information', {'fields': ['pub_date']}) can be displayed as pub_date is Date information.

Add an object in a related table



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


Import the Choice model and add ʻadmin.site.register (Choice). This will allow you to edit the Choicemodel. However, this time it is a relation that there are multiple answers to one question, so it is convenient to be able to add aChoice object along with it when adding a Question` object, so that way I will change it.



from django.contrib import admin

from .models import Choice, Question


class ChoiceInline(admin.TabularInline):
    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)


Set the model and the number of data to be related in the ChoiceInline class (in the above example, one Question object has three fields for the Choice object). If you specify TabularInline as an argument, you can change the appearance of the table format like phpMyAdmin. Fields with 'classes': ['collapse'] are displayed in a collapsed state. Specify the previous ChoiceInline class with ʻinlines = [ChoiceInline]`.

Customize the page that is the index of the model

In fact, if you keep the default, the page that lists the model's records (it seems to be called Change List in Django) will only show one column. This is inconvenient, so let's make it possible to display all the columns of the record. Add the following items to the QuestionAdmin class of ʻadmin.py`.

polls/admin.py



#Specify the column to be displayed in Change List

list_display = ('question_text', 'pub_date', 'was_published_recently')


polls/models.py




class Question(models.Model):
	#Omission
    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?'


Modify the was_published_recently () method of models.py as above. You can customize the method in more detail by adding attributes to it. For example, if you specify short_description, you can change the column name to the specified one. If you specify a column name in ʻadmin_order_field, you can sort (filter) the column on the browser. If you specify the boolean attribute, the XX icon will be displayed instead of True or False. was_published_recently has a value of True or False, so it will be displayed as an icon instead. Let's go back to ʻadmin.py again.

polls/admin.py




from django.contrib import admin
from .models import Question, Choice

# Register your models here.

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

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

admin.site.register(Question, QuestionAdmin)
# admin.site.register(Choice)

The setting of list_filter = ['pub_date'] is the setting to display the filter sidebar together with the setting of ʻadmin_order_fieldearlier. search_fields = ['question_text']is a setting to display the search box. This will allow you to search in theChange List with the search term you put the question_text` column in the search box in this case.

Finally

This completes all 7 chapters of the Django tutorial. However, up to this point, for example, this tutorial has a chapter on testing, deployment, and reuse as a supplementary chapter, and even if you customize the management screen of this chapter, you can use templates, apply CSS, and manage functions. There are many more detailed settings, so there are still many things to do.

As for the impression that I completed the race, I think that Django, including the language Python, is a little difficult to understand for those who started programming from scratch, but on the contrary, it is certain for those who have mastered other languages. I feel that it may be possible to learn at a low learning cost. From now on, I would like to deepen my understanding while creating my own products, including team development projects.

reference

[Python] Django admin site customization (display) [Django admin screen reverse lookup memo] https://qiita.com/zenwerk/items/044c149d93db097cdaf8) Django documentation

Recommended Posts

Learning history for participating in team app development in Python ~ Django Tutorial 5 ~
Learning history for participating in team app development in Python ~ Django Tutorial 4 ~
Learning history for participating in team app development in Python ~ Django Tutorial 6 ~
Learning history for participating in team app development in Python ~ Django Tutorial 7 ~
Learning history for participating in team application development in Python ~ Index page ~
Learning history for participating in team application development in Python ~ Think a little about requirement definition ~
Learning history for participating in team application development in Python ~ Supplement of basic items and construction of jupyterLab environment ~
Learning history to participate in team application development with Python ~ Build Docker / Django / Nginx / MariaDB environment ~
Learning history to participate in team application development in Python ~ After finishing "Introduction to Python 3" of paiza learning ~
Python Django Tutorial (2)
Python Django Tutorial (8)
Python Django Tutorial (6)
Python Django Tutorial (7)
Python Django Tutorial (1)
Python Django tutorial tutorial
Python Django Tutorial (3)
Python Django Tutorial (4)
Boost.NumPy Tutorial for Extending Python in C ++ (Practice)
[Implementation for learning] Implement Stratified Sampling in Python (1)
Learning notes for the migrations feature in the Django framework (2)
Python Django tutorial summary
Build an interactive environment for machine learning in Python
Directory structure for test-driven development using pytest in python
App development to tweet in Python from Visual Studio 2017
Learning notes for the migrations feature in the Django framework (3)
Learning notes for the migrations feature in the Django framework (1)
Deep Learning Experienced in Python Chapter 2 (Materials for Journals)
Framework development in Python
Development environment in Python
AWS SDK for Python (Boto3) development in Visual Studio 2017
Slackbot development in Python
Tutorial for doing Test Driven Development (TDD) in Flask ―― 1 Test Client
Learning flow for Python beginners
Python learning plan for AI learning
Search for strings in Python
Techniques for sorting in Python
Python development in Visual Studio 2017
Qt for Python app self-update
Python Django Tutorial Cheat Sheet
Checkio's recommendation for learning Python
[For organizing] Python development environment
Python development in Visual Studio
About "for _ in range ():" in python
How about Anaconda for building a machine learning environment in Python?
Automatically resize screenshots for the App Store for each screen in Python
EEG analysis in Python: Python MNE tutorial
Implement stacking learning in Python [Kaggle]
Check for external commands in python
8 Frequently Used Commands in Python Django
Web teaching materials for learning Python
Web application development memo in python
[For beginners] Django -Development environment construction-
Python development environment options for May 2020
<For beginners> python library <For machine learning>
Emacs settings for Python development environment
Python: Preprocessing in Machine Learning: Overview
Implemented Perceptron learning rules in Python
Run unittests in Python (for beginners)
Prepare Python development environment for each project in Windows environment (VSCode + virtualEnvWrapper + Pylint)
Development of MTG card evaluation posting site ~ Django app release in 5 weeks ~