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)
https://docs.djangoproject.com/ja/3.0/intro/tutorial07/
This time, the following articles were very helpful throughout! Django Admin Reverse Lookup (Basic)
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)
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.
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:
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.
A changelist page is such a page.
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.
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']
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.
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