715   Django Python

Django 提供了默认页面布局和样式,如何修改样式了?

 

1,先新建自定义样式文件style.css,注意路径

 

$ vim polls/static/polls/style.css
li a {
    color: green;
}

 

2,通过Django的static模块来加载自定义样式

$ vim polls/templates/polls/index.html

{% load static %}



3,重新打开页面 http://localhost:8000/polls/,自定义样式已经生效啦

 

这里修改是Web项目的前台样式,后台admin也是能修改的

1,配置自定义后台页面目录DIRS

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

 

2,新建目录,并复制后台admin默认模版页面 admin/base_site.html

$ ll
manage.py
mysite
polls
$ mkdir -p templates/admin
$ python -c "import django; print(django.__path__)"
['/usr/local/lib/python2.7/site-packages/django']
$ cp /usr/local/lib/python2.7/site-packages/django/contrib/admin/templates/admin/base_site.html templates/admin/

 

3,修改自定义后台模版,将 {{ site_header|default:_(‘Django administration’) }} 改成 Polls administration

{% extends "admin/base.html" %}

{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}

{% block branding %}

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

 

后台admin页面就变成了polls administration 了

 

后台admin的提交表单form不需要通过以上的方法修改;
Django将form表单的布局优化成可配置了

1,更改后台admin查看question的表单

 

$ vim 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)

 
admin08t (1)

 

2,新建question时默认添加Choice

$ vim 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)

 
admin10t
 

是不是感觉方便极了,只需简单配置就能改变后台admin的表单,更多样例请查看官网




Leave a Reply

Your email address will not be published. Required fields are marked *