Writing your first Django app, part 2--学习笔记

一:创建一个管理员账号

budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ python manage.py createsuperuser
Username (leave blank to use 'budong'): admin
Email address: admin@qq.com
Password:
Password (again):
Superuser created successfully.

二:将polls注册到admin面板,以便可以通过admin面板编辑数据

polls/admin.py

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

# Register your models here.

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

class QuestionAdmin(admin.ModelAdmin):
    #fields = ['pub_date','question_text']
    list_display = ('question_text','pub_date','was_published_recently')
    fieldsets = [
            (None,{'fields':['question_text']}),
            ('Date information',{'fields':['pub_date'],'classes':['collapse']}),
            ]
    inlines = [ChoiceInline]
    list_filter = ['pub_date']
    search_fields = ['question_text']

polls/models.py

from django.db import models

import datetime
from django.utils import timezone

# Create your models here.

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

三:修改admin的Django Administration为Polls Administration

1.修改settings.py,新建templates目录

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.复制django的admin模板文件django/contrib/admin/templates/admin/base_site.html到poll_mysite/templates/admin/base_site.html

3.修改base_site.html中第六行Django Administration为Polls Administration


参考资料:

Writing your first Django app, part 2:https://docs.djangoproject.com/en/1.8/intro/tutorial02/