I will continue to play with the admin page.
Last time went to the point of registering Poll, but this time we will also register Choice (Review: Poll and Choice in models.py) One is defined).
You can use it as admin.site.register (Choice), but that will make the Poll and Choice registration screens separate. The relationship between the two is that Poll contains multiple Choices, so I want to create a screen that conforms to that.
admin.py ######
class ChoiceInline(admin.StackedInline): #Is StackedInline an inline format?
model = Choice
extra = 3 #What does it mean to put in how many models?
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline] #Is inline like an additional area?
admin.site.register(Poll, PollAdmin)
#"?" Is added to the end of the comment because I am not confident in my understanding.
Choice can also be registered on the Poll edit screen. If you want to make it more compact, you can set the parent class of ChoiceInline to TabularInline and each Choice will fit in one line.
I'll play with it a little more.
By default, the list display screen only displays each saved data as a character string, but you can add other elements here as well.
To do this, add the following line to the PollAdmin class.
admin.py ######
class PollAdmin(admin.ModelAdmin):
# ...
list_display = ('question', 'pub_date') # list_Specify display with display
#I happened to make a mistake in writing and confirmed the operation even in list format. Is it natural
And if you write like this
list_display = ('question', 'pub_date’,’was_published_recently’)
# was_published_recently is a function defined in Poll (note that recently was today in the previous document)
It seems that it is also possible to display the return value from the function. By the way, the underscore is replaced with a blank.
As a preliminary step, I will add a little Poll model.
models.py ######
from django.utils import timezone
class Poll(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1) #Is it within a day of being published?
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
And you can add options by adding the following to the PollAdmin class.
admin.py ######
list_filter = ['pub_date'] # pub_Function to narrow down based on date
search_fields = ['question'] #Ability to search based on question
date_hierarchy = 'pub_date' #Similar in function to date filter
It seems that you can customize it in more detail by using a template, but I will not touch it this time because I will do it in detail in the next tutorial. And
Enter Tutorial 3. I'm looking forward.
Recommended Posts