ruk·si

🍡 Django Tutorial
Admin Forms

Updated at 2018-11-23 18:31

Edit polls/admin.py:

from django.contrib import admin
from .models import Question


@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    fields = ['text', 'author', 'created_at', 'updated_at']
    readonly_fields = ['created_at', 'updated_at']

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

Or:

from django.contrib import admin
from .models import Question


@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields': ['text', 'author']}),
        ('Date Information', {'fields': ['created_at', 'updated_at']}),
    ]
    readonly_fields = ['created_at', 'updated_at']

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

Edit polls/admin.py:

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


@admin.register(Choice)
class ChoiceAdmin(admin.ModelAdmin):
    pass


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


@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    list_display = (
        'text',
        'author',
        'was_created_recently',
        'created_at',
        'updated_at'
    )
    fieldsets = [
        (None, {'fields': ['text', 'author']}),
        ('Date information', {
            'fields': ['created_at', 'updated_at'],
            'classes': ['collapse']
        }),
    ]
    readonly_fields = ['created_at', 'updated_at']
    inlines = [ChoiceInline]

Edit polls/admin.py - QuestionAdmin:

search_fields = ['text']
list_filter = ['created_at']

Edit polls/models.py: You can customize list field name, field visuals and default ordering.

# ...
    def was_created_recently(self) -> bool:
        return self.created_at >= timezone.now() - timedelta(days=1)

    was_created_recently.admin_order_field = 'created_at'
    was_created_recently.boolean = True
    was_created_recently.short_description = 'Created recently?'ed recently?'
# ...