django第一個app,7

經過admin頁面更好的管理html

分開顯示:python

polls/admin.pydjango

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)

把一對多關聯顯示,這裏額外顯示3個url

polls/admin.pydebug

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)

choice列展現換位橫向展現orm

class ChoiceInline(admin.TabularInline):

在數據列表裏面展現更多的信息,字段和方法均可以htm

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

點擊字段名是自帶排序的,除了方法,沒有肯定的返回值,不能排序,咱們能夠這樣排序

定義某字段的排序值爲別的值,ip

改變值爲布爾值字符串

改嗎字段顯示名稱

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?'

添加一個篩選條件

list_filter = ['pub_date']

添加一個搜索條件,彷佛只能添加一個字符串的搜索條件

search_fields = ['question_text']

查找import包的路徑,好比django

python -c "import django; print(django.__path__)"

設定項目本身的templates

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',
            ],
        },
    },
]

在manage.py同目錄下建立templates/admin。複製django自帶的目錄下的base_site.html複製到admin文件下,改變內容

{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>
{% endblock %}

項目會自動覆蓋原django的文件,而展現這個文件內容,通常最重要的是admin下的index.html,也能夠像這樣覆蓋。

相關文章
相關標籤/搜索