天天看點

django學習筆記(2)

Part 2: The admin site

====> Creating an admin user

$ python manage.py createsuperuser

   Username: admin

   Email address: [email protected]

   Password: **********

   Password (again): *********

   Superuser created successfully.

====> Start the development server

$ python manage.py runserver

====> Enter the admin site

(http://127.0.0.1:8000/admin/)

====> Make the poll app modifiable in the admin

$ edit polls\admin.py

from django.contrib import admin

from .models import Question

admin.site.register(Question)

====> Explore the free admin functionality

====> Customize the admin form

class QuestionAdmin(admin.ModelAdmin):

    fields = ['pub_date', 'question_text']

admin.site.register(Question, QuestionAdmin)

====> Split the form up into fieldsets

    fieldsets = [

        (None,               {'fields': ['question_text']}),

        ('Date information', {'fields': ['pub_date']}),

    ]

====> Assign arbitrary HTML classes to each fieldset

        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),

====> Adding related objects

from .models import Choice, Question

# ...

admin.site.register(Choice)

====> Remove the register() call for the Choice model. Then, change the Question registration code

class ChoiceInline(admin.StackedInline):

    model = Choice

    extra = 3

    inlines = [ChoiceInline]

====> Change the display style of the related objects in a more compact, table-based format

class ChoiceInline(admin.TabularInline):

    #...

====> Customize the admin change list -- use the list_display admin option

    # ...

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

====> Add a “Filter” sidebar -- using the list_filter admin option

    list_filter = ['pub_date']

====> Add some search capability

    search_fields = ['question_text']

====> Customize the admin look and feel

====> Customizing your project’s templates

$ mkdir templates

$ edit mysite\settings.py

TEMPLATES = [

    {

        # ...

        'DIRS': [os.path.join(BASE_DIR, 'templates')],

    },

]

$ mkdir templates\admin

$ copy C:\python34\lib\site-p~1\django\contrib\admin\templates\amdin\base_site.html templates\admin\base_site.html

$ edit tempaltes\admin\base_site.html

# replace {{ site_header|default:_('Django administration') }} with Polls Administration

{% block branding %}

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

{% endblock %}

====> Customizing your application’s templates

====> Customize the admin index page