您的位置:首页 > 编程语言 > Go语言

Ubuntu12.04系统下写你的第一个Django1.5应用(二)--admin

2013-03-14 23:11 513 查看
Ubuntu12.04系统下写你的第一个Django1.5应用(二)

激活admin site

第一步:修改settings.py文件,解INSTALLED_APPS中的注释:

jiangge@ubuntu:~/mysite/mysite$ vim settings.py


# Uncomment the next line to enable the admin:
'django.contrib.admin',


第二步:因为新添加了app,所以数据库中的表需要更新,命令行输入:

jiangge@ubuntu:~/mysite$ python manage.py syncdb


第三步:编辑url文件,解注释

jiangge@ubuntu:~/mysite/mysite$ vim urls.py


from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()  

urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),

# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

   # Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)






启动开发服务器:

命令行输入

jiangge@ubuntu:~/mysite$ python manage.py runserver
浏览器地址栏输入:
http://127.0.0.1:8000/admin/
这时会看到登录界面了.

登录admin site

还记得在上篇文章里创建的超级用户的,用户名,和密码吗?试试用它们登录吧.

NOTE:如果当时忘记创建了,可以Creating superusers,详情参考点击打开链接  




manage.py createsuperuser --username=joe --email=joe@example.com


登录后你可以看到:用户, 组, 站点等等.

使得poll app 在 admin中可修改

第一步:在polls目录下创建一个 admin.py的文件:

jiangge@ubuntu:~/mysite/polls$ vim admin.py
加入以下内容到文件中:

from django.contrib import admin
from polls.models import Poll

admin.site.register(Poll)


第二步:重启开发服务器:(一般来说,修改文件后,服务器会自动重启.但是,新添加了文件,它不会自动重启,所以需要手动启动哦.)

jiangge@ubuntu:~/mysite$ python manage.py runserver


第三步:浏览器地址栏输入:

http://127.0.0.1:8000/admin
因为我们已经注册 Poll到admin中,所以现在就可以看到结果了.

观察输入框和按钮,试着修改,添加,删除些内容吧.

自定义 admin form

jiangge@ubuntu:~/mysite/polls$ vim admin.py


Replacethe admin.site.register(Poll) line with red code:

from django.contrib import admin
from polls.models import Poll

class PollAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question']

admin.site.register(Poll, PollAdmin)


以上改动,使得“Publication date” come before the“Question” field.

--------------------------------------

from django.contrib import admin
from polls.models import Poll

class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None,               {'fields': ['question']}),
('Date information', {'fields': ['pub_date']}),
]

admin.site.register(Poll, PollAdmin)


Date information 数据太长的话,可以隐藏,显示

from django.contrib import admin
from polls.models import Poll

class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None,               {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]

admin.site.register(Poll, PollAdmin)


添加相关的对象:

第一种方法

from django.contrib import admin
from polls.models import Poll
from polls.models import Choice

class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None,               {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]

admin.site.register(Poll, PollAdmin)
admin.site.register(Choice)


Now “Choices” is an available option in the Django admin. The “Add choice” formlooks like this:

第二种方法:

Remove the register() call for theChoice model. Then, edit thePollregistration
code to read:

from django.contrib import admin
from polls.models import Choice, Poll

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

class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None,               {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]

admin.site.register(Poll, PollAdmin)
admin.site.register(Choice)
This tells Django: “Choice objects are edited on thePoll admin page. Bydefault, provide enough fields for 3 choices.”

It works like this: There are three slots for related Choices – as specifiedbyextra – and each time you come back to the “Change” page for analready-created object, you get another three extra slots.

At the end of the three current slots you will find an “Add another Choice”link. If you click on it, a new slot will be added. If you want to remove theadded slot, you can click on the X to the top right of the added slot. Notethat you can’t remove the original
three slots

from django.contrib import admin
from polls.models import Choice, Poll

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

class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None,               {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]

admin.site.register(Poll, PollAdmin)
admin.site.register(Choice)
With that TabularInline (instead ofStackedInline), therelated objects are displayed in a more compact, table-based format

Customize the admin change list 自定义

from django.contrib import admin
from polls.models import Choice, Poll

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

class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None,               {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question', 'pub_date','was_published_recently')

admin.site.register(Poll, PollAdmin)
admin.site.register(Choice)


modles.py

#coding:utf-8

from django.db import models
import datetime
from django.utils import timezone

class Poll(models.Model):
question = 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 __unicode__(self):
return self.question

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

def __unicode__(self):
return self.choice_text


编辑admin.py文件,增加过滤

from django.contrib import admin
from polls.models import Choice, Poll

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

class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None,               {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question', 'pub_date','was_published_recently')
list_filter = ['pub_date']
admin.site.register(Poll, PollAdmin)
admin.site.register(Choice)
注:That adds a “Filter” sidebar that lets people filter the change list by thepub_date field:

增加搜索框:

from django.contrib import admin
from polls.models import Choice, Poll

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

class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None,               {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question', 'pub_date','was_published_recently')
list_filter = ['pub_date']
search_fields = ['question']
admin.site.register(Poll, PollAdmin)
admin.site.register(Choice)


添加阶层式导航 hierarchical navigation

from django.contrib import admin
from polls.models import Choice, Poll

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

class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None,               {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question', 'pub_date','was_published_recently')
list_filter = ['pub_date']
search_fields = ['question']
date_hierarchy = 'pub_date'
admin.site.register(Poll, PollAdmin)
admin.site.register(Choice)


That adds hierarchical navigation, by date, to the top of the change list page.At top level, it displays all available years. Then it drills down to monthsand, ultimately, days.

自定义外观和感觉:
自定义你的项目模板:
在项目目录下创建一个templates目录.(keeping your templates within the project is a good convention to follow.)

jiangge@ubuntu:~/mysite$ mkdir templates


修改settings.py

TEMPLATE_DIRS = (
 '/home/jiangge/mysite/templates',  
# Put strings here, like "/home/html/django_templates" or "C:/www/django/te>
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)


复制:

Now copy the template
admin/base_site.html from within the default Django admin template directory in the source code of Django itself(django/contrib/admin/templates)into
an admin subdirectory of whichever directory you’re using inTEMPLATE_DIRS.
For example, if yourTEMPLATE_DIRS includes'/path/to/mysite/templates',
as above, then copydjango/contrib/admin/templates/admin/base_site.html to/path/to/mysite/templates/admin/base_site.html. Don’t forget thatadmin
subdirectory.

提示:不知道Django源文件在哪里?在命令行输入:

python -c "
import sys
sys.path = sys.path[1:]
import django
print(django.__path__)"
回车,就可以看到结果了:

['/usr/local/lib/python2.7/dist-packages/Django-1.5.dev20120922131713-py2.7.egg/django']


复制地址好长啊.....:

cp /usr/local/lib/python2.7/dist-packages/Django-1.5.dev20120922131713-py2.7.egg/django/contrib/admin/templates/admin/base_site.html
/home/jiangge/mysite/templates/admin/base_site.html


Note that any of Django’s default admin templates can be overridden. To override a template, just do the same thing you did withbase_site.html –copy it from the default directory into your
custom directory, and make changes.


Customizing your application’s templates

See the
template loader documentation for moreinformation about how Django finds its templates.点击打开链接

Customize the admin index page

The template to customize is admin/index.html. (Do the same as withadmin/base_site.html in the previous section – copy it from the defaultdirectory
to your custom template directory.)

----------------------------------------------------------------------------------------------------------------------

本文由@易枭寒(499065469@qq.com)

官网原文地址:https://docs.djangoproject.com/en/1.5/intro/tutorial02/#customize-the-admin-look-and-feel点击打开链接


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  django