part 二是關於django的自帶的管理員界面
在這裏提醒以下,昨天創建數據庫的時候忘了說一點,今天把我自己也坑了, 關於如果要在數據庫裏插入中文的話,
一開始創建數據庫的時候就要加上 create database name default charset=utf8
我的處理辦法可能比較複雜,刪了原本的數據庫(幸好沒有往裏邊插數據)
然後再重新創建一次,
回到命令號, python manage.py makemigrations
python manage.py migrate
可以 python manage.py createsuperuser 創建管理員,然後會讓你輸入用戶名, 郵箱, 密碼
也可以 python manage.py syncdb 數據庫同步完成之後會出現與 createsuperuser相同的界面
然後python manage.py runserver
瀏覽器打開 127,0,0.1:8000/admin
就可以看到登錄界面了
有的打開可能是英文界面, 這就要到settings.py 裏邊修改配置文件了,編碼改爲 'zh-c' LANGUAGE_CODE = 'zh-cn'
登錄進去之後我們看到的界面是這樣的
並沒有我們創建的表
可以這樣
在polls 的admin.py中加入下邊一行
from polls.models import Question admin.site.register(Question)
出現了我們問題的管理界面
然後下邊一堆關於怎麼優化管理員界面青自行參閱django官方文檔tutorial ,直接展示結果,(對書中作出了部分改動),優化了關於中文顯示部分
models.py
#coding=utf-8
from django.db import models
from django.utils import timezone
import datetime
class Question(models.Model):
question_text = models.CharField("問題描述", max_length=200)
pub_date = models.DateTimeField("更新日期")
def __unicode__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
list_display = ('question_text', 'pub_date', 'was_published_recently')
was_published_recently.admin_order_field = 'pub_date'
#was_published_recently.boolean = True
was_published_recently.short_description = '近期發佈?'
Question.short_description = "問題"
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField("選項", max_length=200)
votes = models.IntegerField("票數", default=0)
def __unicode__ (self):
return self.choice_text
admin.py
#coding=utf8
from django.contrib import admin
from polls.models import Question, Choice
#class QuestionAdmin(admin.ModelAdmin):
# fields = ['pub_date', 'question_text']
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
("問題設置", {'fields':['question_text']}),
('日期信息', {'fields':['pub_date'], 'classes':['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
#search_fields = ['pub_date']
search_fields = ['question_text']
admin.site.register(Question, QuestionAdmin)
最終結果如上,感覺還是不錯的,(注意上邊的顯示不是中文亂碼, 是我手打隨意打的)
最後文檔介紹了一點有意思的東西, 重載管理員界面模板,每次管理員上來都看到django管理, 原文說這是ridiculous ,其實是山寨氣息濃厚~
在工程的根目錄下創建目錄templates/admin
並且把在settings裏邊加入
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
在django 的 安裝目錄下,不知道django的安裝目錄可以這樣,
python
import sys sys.path = sys.path[1:] import django print(django.__path__)" 然後把django/contrib/admin/templates admin/base_site.html 複製到我們創建的目錄下templates/admin 把我的裏邊的文件改爲 {% extends "admin/base.html" %} {% block title %}投票管理{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}"><h1 id="site-name"><a href="{% url 'admin:index' %}">投票管理</a></h1></a></h1> {% endblock %} {% block nav-global %}{% endblock %} 這樣出來的就不知django管理了,這少不是那麼山寨了~