Python Django Tutorial (2)

This is a material for study sessions. I will explain while following the tutorial of django1.8. https://docs.djangoproject.com/en/1.8/intro/tutorial02/

Since version 1.4 is the latest version of the official Japanese document, there are some differences, but the general flow is the same, so it's a good idea to read it. http://django-docs-ja.readthedocs.org/en/latest/intro/tutorial02.html

Tutorial 1Tutorial Summary

Overview

This time, I will explain about the django management site. A management site is provided as standard in django, and users with staff privileges can operate the model from here. Models that you have added, including the standard user model that django has (For example, the two models for voting created in the tutorial) also semi-automatically create a page like that.

If it is a web application that only handles data such as registering data, displaying a list, and searching You can easily create it just by customizing this page.

Preparation of super user

Documents → https://docs.djangoproject.com/en/1.8/intro/tutorial02/#creating-an-admin-user Source → ʻadd_app_4_database_migration` tag (no change)

A user with staff authority is required to touch the management site. A superuser for django is created using the createsuperuser command.

$ ./manage.py createsuperuser
Username (leave blank to use 'shimomura'): admin
Email address:
Password:
Password (again):
Superuser created successfully.

When you execute the createsuperuser command, you will be prompted to enter your Username, Email, and Password. If the Username is default, the PC username will be entered as it is. This time it is ʻadmin`. Email can be empty. For Password, enter the same character string twice.

Finally, when Superuser created successfully. appears, the process is complete.

Access the management site

Documents → https://docs.djangoproject.com/en/1.8/intro/tutorial02/#start-the-development-server Source → ʻadd_app_4_database_migrationtag →954ba86`

After creating a super user, start the test server and access the management site. To start the server, use the runserver command.

$ ./manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
November 05, 2015 - 07:37:15
Django version 1.8.5, using settings 'tutorial.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

In this state with a browser http://localhost:8000/admin/ When you access, you should be redirected to the login screen as shown below.

Kobito.b0bz7R.png

If you can log in successfully, the following screen will be displayed. By default, only the authentication models (Groups and Users) are displayed.

Kobito.WQw8Oi.png

--

Localizing into Japanese

I think I was able to display the site safely, but as you can see, the management site is in English by default. I don't like English, so let's use Japanese.

Of course, django supports multiple languages. The language to be displayed is defined near line 103 of settings.py. The default is ʻen-us, so let's change this to ja`.

settings.py_Near line 103


# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'ja'

# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Tokyo'

After fixing it, please try to access the management site again. http://localhost:8000/admin/

Kobito.dVaOZw.png

It seems that it has been successfully translated into Japanese.

Voting model added

Documents → https://docs.djangoproject.com/en/1.8/intro/tutorial02/#make-the-poll-app-modifiable-in-the-admin Source → 954ba86 35ec2c6

Now that you can see the management site safely, let's display your own model as well. Set and customize the model to be displayed on the management site in ʻapp / admin.py`.

This time, we will add the Question model of the polls application following the tutorial.

polls/admin.py


from django.contrib import admin

from .models import Question


admin.site.register(Question)

It should now be visible on the admin site.

Kobito.Q3fesY.png

Add and customize data

Add data

Let's try adding data as well. When you press the add link, the form for adding data will be displayed. The Question model had two fields, question_text and pub_date, so Two items are also displayed on the form display.

Kobito.24CSrL.png

Kobito.dMucDK.png

When you register, you should have one data called Question object. If you register again, two Question objects will be displayed.

Kobito.eBQJpR.png

Object name customization

Since we do not know what kind of data this is, let's change the character string that represents the object. To change it, just override the __str__ method (__unicode__ in the case of python2 series) of the model you want to change. This time, we will modify it so that the question content is displayed.

polls/models.py


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

Kobito.ilTlCf.png

Customize model name

If you want to change the character string (Question in this case) that represents the model itself, set it in the Meta </ b> class. The name that represents the model with verbose_name, You can set the plural name of the model with verbose_name_plural.

polls/models.py


class Question(models.Model):
    class Meta:
        verbose_name = 'Question'
        verbose_name_plural = 'Plural of questions'

    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

Kobito.r2Xvyz.png

Make sure that Question, Questions is changed to Question,` question plural``.

Customize the order

By default, the order of registration is descending (newest ones come up), but let's change this so that it is sorted from the newest one on the publication date (pub_date).

Changes are set in the ʻorderingproperty of the model's Meta class. The setting value is the field name, and if you want to sort in descending order, add-` at the beginning.

class Question(models.Model):
    class Meta:
        verbose_name = 'Question'
        verbose_name_plural = 'Plural of questions'
        ordering = ['-pub_date']

    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

First, if you want to sort the questions in descending order of the release date ordering = ['question_text', '-pubdate'] Write as follows. Please check that they are actually rearranged.

--

It is also possible to customize the form itself when adding. (Explained in the next section below) In the original tutorial, when adding a Question object after this I explain how to change the design of Form, but I will omit the explanation this time. If you are interested, please see the tutorial of the head family. https://docs.djangoproject.com/en/1.8/intro/tutorial02/#customize-the-admin-form

Object with relation

Documents → https://docs.djangoproject.com/en/1.8/intro/tutorial02/#adding-related-objects (Explained in ʻAdd Inline itemfrom the middle) Source →35ec2c6 84f1086`

We will add another model, Choice, which the polls app has. This model has a Foreign Key (relationship to the Question model), what does it look like?

First, edit polls / admin.py and add Choice to display it in admin.

polls/admin.py


from django.contrib import admin

from .models import Question
from .models import Choice  #Add here


admin.site.register(Question)
admin.site.register(Choice)  #Add here

Kobito.yD8Cfw.png

It seems that it was added safely. The Choice model does not have Meta settings, so it comes out as it is. Next, we will look at the additional screen.

Kobito.dfblb5.png

In the case of ForeignKey field, it is displayed as a select list in Form like this. You can also create a new Question object by pressing the green plus button on the right.

Kobito.DcXGUI.png

The content contains the Question model object created earlier like this. If you haven't set __str__, all three will be displayed as Question object and you will be sad. Of course, you can freely customize what you want to offer with this option. The order is sorted by ʻordering` set in the Meta class of the model.

Model customization for Admin site

In this way, just registering the model with the ʻadmin.site.register` function will do various things automatically, but With a little modification, you can customize the contents of the Form, display the list, add search items, and so on.

When customizing, pass the class that describes the behavior at the Admin site as the second argument of the ʻadmin.site.reigster function. This class inherits the ʻadmin.ModelAdmin class and overrides only the necessary parts by yourself. Since it is difficult to understand if it is only sentences, we will actually show examples of each customization.

Add Inline item

Documents → https://docs.djangoproject.com/en/1.8/intro/tutorial02/#adding-related-objects Source → 84f1086 → ʻe4bacf7`

In the examples so far, if you want to add Questions and Choices, first create the original Question and then I had to select it on the additional page of Choice. It is troublesome to select Question one by one in Choice, and there is a possibility of making a mistake in selection.

Inline Form is convenient there. If you use this, you can use the relation source object (Question in this case) You can create the relation destination object (Choice in this case) at the same time.

In the case of the admin site, a class for displaying Inline called InlineAdmin is prepared. This time we will use the StackedInline class.

The modified source code is as follows.

polls/admin.py


from django.contrib import admin

from .models import Question
from .models import Choice


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


class QuestionAdmin(admin.ModelAdmin):
    inlines = [ChoiceInline]

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

Add the definitions of ChoiceInline and QuestionAdmin and add them to the second argument when registering the Question. It is modified to pass QuestionAdmin.

ʻAdmin.StackedInline` is a base class for creating Stacked format Inline. Set the target model (Choice in this case) and the number of displays (extra = 3). You can also set the maximum number and whether or not it can be deleted.

ʻAdmin.ModelAdmin` is a class for customizing the behavior of the model on the admin site. This time, inlines are set, and the behavior when adding and editing objects is changed.

If you change so far and go to the additional page (or edit page) of Question on the management site again You can see that you can edit Choices at the same time.

Kobito.3GQrd4.png

Customize object display

Documents → https://docs.djangoproject.com/en/1.8/intro/tutorial02/#customize-the-admin-change-list Source → ʻe4bacf77f5128a`

Now that registration and editing are getting better, let's customize the list display. To change the display, set list_display in the class (QuestionAdmin) created by inheriting ʻadmin.ModelAdmin`.

polls/admin.py


...
class QuestionAdmin(admin.ModelAdmin):
    inlines = [ChoiceInline]
    list_display = ('question_text', 'pub_date')
...

Kobito.2sV4uA.png

The list, which was a murderous landscape, has become a little more lively. For all models, django will automatically give you a primary key. As a side note, let's add that as well.

polls/admin.py


...
class QuestionAdmin(admin.ModelAdmin):
    inlines = [ChoiceInline]
    list_display = ('pk', 'question_text', 'pub_date')
...

Kobito.MR1ddC.png

it is a good feeling.

More customization

Let's do something a little special, following the original tutorial. In addition to fields, list_display can be set to a method with no arguments.

Add a was_published_recently method to the Question model to see if the question was published within a day.

polls/models.py


import datetime

from django.db import models
from django.utils import timezone


class Question(models.Model):
...

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
...

Next, add this method to list_display.

polls/admin.py


...
class QuestionAdmin(admin.ModelAdmin):
    inlines = [ChoiceInline]
    list_display = ('pk', 'question_text', 'pub_date', 'was_published_recently')
...

Kobito.gpHA62.png

You can see it properly. It may be interesting to create a method that returns the number of Choices associated with the Question.

Further customization

If the target of list_display is a method, you can change the display and set order conditions by adding attributes to the method. Let's set ʻadmin_order_field, boolean, short_description` by following the original tutorial.

polls/models.py


...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'
...

Kobito.qOD9IC.png

It feels very good. ʻAdmin_order_fieldsets which field to look at when sorting. In this example, they are sorted by thepub_date` field. By setting this attribute, you can click the header of the table and sort it.

Filter, add search

Finally, let's add a filter and a search. Just set the property in QuestionAdmin as in the example.

polls/admin.py


...
class QuestionAdmin(admin.ModelAdmin):
    inlines = [ChoiceInline]
    list_display = ('pk', 'question_text', 'pub_date', 'was_published_recently')
    list_filter = ['pub_date']
    search_fields = ['question_text']
...

Kobito.SrObQZ.png

You can easily add filters and searches like this.

-- To the next tutorial

Tutorial Summary

Recommended Posts

Python Django Tutorial (5)
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)
Python Django tutorial summary
Python tutorial
Python Django Tutorial Cheat Sheet
Python tutorial summary
django tutorial memo
Start Django Tutorial 1
Django 1.11 started with Python3.6
[Docker] Tutorial (Python + php)
Django python web framework
Django Polymorphic Associations Tutorial
django oscar simple tutorial
Django Python shift table
Try Debian + Python 3.4 + django1.7 ...
[Personal notes] Python, Django
Python OpenCV tutorial memo
[Python tutorial] Data structure
Django Girls Tutorial Note
Cloud Run tutorial (python)
Python Django CSS reflected
Do Django with CodeStar (Python3.6.8, Django2.2.9)
Get started with Django! ~ Tutorial ⑤ ~
Introduction to Python Django (2) Win
[Python tutorial] Control structure tool
Python
Do Django with CodeStar (Python3.8, Django2.1.15)
Python3 + Django ~ Mac ~ with Apache
Create ToDo List [Python Django]
Getting Started with Python Django (1)
Get started with Django! ~ Tutorial ④ ~
Django
Getting Started with Python Django (4)
Getting Started with Python Django (3)
Get started with Django! ~ Tutorial ⑥ ~
Install Python 3.7 and Django 3.0 (CentOS)
[Python] Decision Tree Personal Tutorial
GAE + python + Django addictive story
Getting Started with Python Django (6)
Getting Started with Python Django (5)
Until Python [Django] de Web service is released [Tutorial, Part 1]
EEG analysis in Python: Python MNE tutorial
Python practice_Virtual environment setup ~ Django installation
Create new application use python, django
python + django + scikit-learn + mecab (1) on heroku
python + django + scikit-learn + mecab (2) on heroku
Run python3 Django1.9 with mod_wsgi (deploy)
Django Girls Tutorial Summary First Half
Stumble when doing the django 1.7 tutorial
Deploy the Django tutorial to IIS ①
Install Python framework django using pip
Introduction to Python Django (2) Mac Edition
[Python Tutorial] An Easy Introduction to Python
Learning history for participating in team app development in Python ~ Django Tutorial 5 ~