[翻译]Django 1.0 中文文档—–指导 第二部分 自动生成管理工具

编写你第一个Django应用,第二部分

我们接着上篇指导开始,我们继续这个网页投票应用,致力于Django自动管理接口部分。

理念 

为你的工作人员和客户开发一个网站增删改管理是一个单调乏味无创意的工作,因此Django实现了完全自动的做到了自动创建模型管理接口的功能。

Django在新闻工作室环境中诞生,他很明确的将内容发布人员和网站分割开来,网站管理人员通过系统发布新闻报道,时间,体育赛事等等,这些内容被显示在网站上,django解决了通过统一管理接口编辑网站内容。

网站管理是为管理人员提供的,对网站访问用户是不需要的。

 

激活管理系统

 

Django管理系统默认是没有激活的,如果你要安装激活他需要做下面三件事。

 

  • 添加 "django.contrib.admin" 到你的 INSTALLED_APPS 设置里
  • 运行 python manage.py syncdb . 在你加入新的应用到 INSTALLED_APPS , 数据库表需要更新
  • 编辑 mysite/urls.py 文件 取消 “Uncomment the next two lines…” 下面的注释, 这是个URL配置文件; 我们将会在下篇指导中讲述URL. 现在, 我们需要如下修改urls.py文件。

 

from django.conf.urls.defaults import *

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

urlpatterns = patterns('',
    # Example:
    # (r'^mysite/', include('mysite.foo.urls')),

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

    # Uncomment the next line to enable the admin:
    (r'^admin/(.*)', admin.site.root),

)

加粗的几行就是需要取消注释的部分。

 

启动服务

 

我们启动服务查看管理接口。

像指导第一部分里提到的那样执行

 

python manage.py runserver

 

现在我们在浏览器里访问地址 http://127.0.0.1:8000/admin/ 你应该会看到下面的登陆页面

 

Django admin login screen

 

进入管理系统

 

现在登陆进去,账号就是在上篇里创建(syncdb)的账号,你会看到下面的页面

 

Django admin index page

 

你会看到其他几个内容,用户,用户组,网站。这几个功能是Django默认提供的。

 

将投票应用加入到管理

 

你会发现投票应用没有在管理界面上。

 

需要做一件事,我们需要把投票poll对象注册到管理接口,在工程polls 目录里我们创建admin.py 文件,编辑为以下内容

 

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

admin.site.register(Poll)

你需要重新启动服务,通常文件被修改后服务会自动重新加载,但是创建新文件服务不会自动重新加载。

 

查看自由的管理功能

 

现在我们注册完poll,Django知道要把他显示在管理界面上。

 

Django admin index page, now with polls displayed

 

点击”Polls.” 进入polls的修改列表页面,这里显示了数据库里所有的polls,你可以选择一个进行修改,有个“What’s up”记录是我们前面创建的。

 

Polls change list page

 

点击“What’s up”记录修改,进入编辑页面

 

Editing form for poll object

 

注意事项

 

  • 表单是根据poll模型自动生成的。
  • 不同的字段类型(DateTimeField CharField ) 相当于相应的html输入组件. 每种字段类型知道如何显示在管理页面上
  • 每个DateTimeField 有自由的javascript快捷组件. 日期有个”Today” 快捷输入和一个日期弹出组件, 时间有个 “Now” 快捷输入和一个时间弹出输入组件.

 

在底部页面给出几个选项

 

  • Save — 保存修改并返回这个对象的列表.
  • Save and continue editing — 保存并继续修改
  • Save and add another — 保存并继续添加新记录
  • Delete — 进入一个删除确认页面.

 

点击”Today” 和 “Now”改变”Date published”,然后点击 “Save and continue editing.”,然后点击页面右上角”History” ,
你会看到一个修改日志的列表,包含时间修改人用户名,这是管理系统自动记录的。

 

History page for poll object

 

自定义管理界面表单

 

仅仅几分钟的时间,你会惊奇的发现实现这些功能你没有写代码,当你调用admin.site.register(Poll),django就会让你能编辑对象,并能猜到如何显示在管理界面中,通常你会需要控制管理界面的显示和工作,当你注册对象到管理接口,你可以设置一些选项。

 

让我们看下如何通过定制表单字段工作,用下面代码替换admin.site.register(Poll):

 

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

admin.site.register(Poll, PollAdmin)

遵循这个方式,创建一个管理对象模型,以第二个参数传递给admin.site.register(),你可以用这个对象修改管理选项。

这个修改使表单里”Publication date”显示在’que stion’的上方

 

Fields have been reordered

当然只有两个字段这个功能不会让人深刻,如果一个表单有好多字段,排序就显得很重要很实用。

 

字段数量多的表单,可以分割多个字段组

 

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

admin.site.register(Poll, PollAdmin)

 

Form has fieldsets now

 

你可以为每个字段组随意指定classes,django提供”collapse” class显示特别的字段组,当表单很长的时候,这个功能就很重要了。

 

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

 

Fieldset is initially collapsed

添加关系对象

 

好,我们已经有了polls管理界面,但是poll有多个选项,管理界面还没有显示选项编辑。

有两个方法

首先注册Choice

 

from mysite.polls.models import Choice

admin.site.register(Choice)

现在choice显示出来

 

Choice admin page

 

在这个表单里,”Poll” 字段selectbox包含数据库所有Polls,django知道如何描述外键,使用select box,在这里目前只有一个poll选项。

 

也注意一下poll旁边的”Add Another”,每个对象都可以通过外键自由关联,当你点击”Add Another”会弹出页面显示一个增加POLL的表单,你添加一个POLL后,DJANGO会自动的把新加的POLL也添加到ADD CHOICE 表单POLL下拉表中。

 

但是,实际上这样添加投票选项是个低效率的办法,有更好的批量添加选项的方法。

去掉 register() ,作一下修改

 

 

 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)

这样告诉DJANGO 在POLL编辑页面上默认提供3个选项表单。如下

Add poll page now has choices on it

这样的话就可以一次添加三个,不过还是有一点不足,这样比较站屏幕,我们对ChoiceInline做下修改

 class ChoiceInline(admin.TabularInline):
     #...

用 TabularInline 代替 StackedInline 显示布局如下

 

Add poll page now has more compact choices

自定义管理界面修改列表

现在poll的管理界面看着已经不错了,我门拉伸下修改列表页面,现在是下面这个样子:

Polls change list page

 

默认情况下 DJANGO 显示 对象的str(),但是有时候一个个显示出需要的字段是很有帮助的,我们使用 list_display管理选项

 class PollAdmin(admin.ModelAdmin):
     # ...
     list_display = ('question', 'pub_date')

 好的 在把 was_published_today 也包含进来

 

 class PollAdmin(admin.ModelAdmin):
     # ...
     list_display = ('question', 'pub_date', 'was_published_today')

Polls change list page, updated
点击列表上的列标题可以针对相应的列排序除了was_published_today,因为他不是数据库字段,默认情况下
was_published_today标题会用替换下划线为空格后的字符串,当然这个我们也可以自定义

 

 def was_published_today(self):
     return self.pub_date.date() == datetime.date.today()
 was_published_today.short_description = 'Published today?'

让我们继续改进POLL修改列表,增加过滤。

  list_filter = ['pub_date']

右边增加了一个导航条

Polls change list page, updated
DJANGO默认给了几个选项 “Any date,” “Today,” “Past 7 days,” “This month,” “This year.”

这样不错,我们再加个搜索功能

 search_fields = ['question']

这样会在顶部添加一个搜索框,同样可以加入其他字段查询,因为这里用的是like查询,所以要合理使用。

自定义管理界面外观

确实,每个管理页面标题都是 “Django administration”是不合适的,这个很容易修改,
打开配置文件 mysite/settings.py,找到 TEMPLATE_DIRS 设置, TEMPLATE_DIRS 里配置一些路径,当DJANGO 加载的时候,会到这些路径里查找模板。

默认TEMPLATE_DIRS   是空的,我们添加自己的模板路径。如下:

 TEMPLATE_DIRS = (
     "/home/my_username/mytemplates", # Change this to your own directory.
 )
现在从你的DJANGO路径里复制admin/base_site.html 到你的工程模板目录里
/home/my_username/mytemplates/admin/base_site.html .
然后修改文件替换为你的标题,这样 base_site.html 就被现在的覆盖了 ,DJANGO 是先查找工程模板目录是否有模板页面。自定义管理页面首页

做法和上面类似

42 thoughts on “[翻译]Django 1.0 中文文档—–指导 第二部分 自动生成管理工具”

  1. I do trust all of the ideas you’ve offered for your post. They are very convincing and can definitely work. Nonetheless, the posts are too short for novices. May you please lengthen them a little from subsequent time? Thanks for the post.

  2. I simply want to say I am all new to blogging and site-building and certainly enjoyed you’re blog. Probably I’m want to bookmark your blog post . You certainly have very good posts. Kudos for revealing your blog site.

  3. You are so awesome! I do not think I’ve read through a single thing like this before. So wonderful to find another person with unique thoughts on this subject. Seriously.. thank you for starting this up. This website is something that is required on the web, someone with a bit of originality.

  4. Greetings! Very useful advice in this particular article! It is the little changes which will make the most important changes. Thanks for sharing!

  5. I have to show some appreciation to this writer just for bailing me out of this type of instance. Just after searching throughout the world wide web and getting views which are not productive, I assumed my entire life was gone. Existing minus the strategies to the difficulties you’ve resolved all through this posting is a critical case, and the kind that might have in a wrong way affected my entire career if I had not discovered the website. Your good understanding and kindness in playing with the whole thing was tremendous. I’m not sure what I would’ve done if I had not discovered such a solution like this. I can also at this point relish my future. Thanks so much for this expert and result oriented help. I will not hesitate to propose your site to anybody who should have support about this subject matter.

  6. I wanted to write you one bit of word to say thank you the moment again over the breathtaking information you have featured in this case. It has been really seriously open-handed of people like you to provide unreservedly just what numerous people could have advertised as an electronic book in order to make some profit for their own end, specifically given that you might well have done it if you decided. The techniques as well worked to be a great way to understand that other people have similar fervor much like my own to realize much more in respect of this matter. I know there are several more enjoyable periods ahead for people who read your site.

  7. Needed to put you a very small note to finally thank you yet again for these extraordinary solutions you’ve contributed on this website. It’s certainly seriously open-handed with people like you to convey freely precisely what a number of people would’ve sold as an ebook to generate some cash for their own end, specifically given that you could have tried it in case you decided. The solutions also acted like the fantastic way to be sure that other people have a similar zeal much like mine to realize more and more related to this condition. I am certain there are some more pleasurable sessions in the future for individuals that looked at your blog post.

  8. I truly wanted to type a simple comment to say thanks to you for all of the wonderful steps you are sharing at this site. My time consuming internet investigation has at the end been compensated with brilliant facts and strategies to write about with my partners. I ‘d suppose that many of us readers are really endowed to exist in a magnificent network with many wonderful individuals with interesting methods. I feel somewhat lucky to have discovered your entire webpage and look forward to many more excellent minutes reading here. Thanks a lot once more for all the details.

  9. I have to express my thanks to this writer for bailing me out of such a crisis. As a result of checking throughout the internet and finding tricks which are not powerful, I assumed my life was well over. Existing devoid of the answers to the problems you have fixed as a result of your entire report is a serious case, and those which might have adversely affected my entire career if I hadn’t discovered your web page. That competence and kindness in handling a lot of things was excellent. I don’t know what I would have done if I had not encountered such a stuff like this. I am able to now look forward to my future. Thanks for your time so much for your high quality and effective help. I will not be reluctant to endorse your web blog to anybody who should get care on this subject matter.

  10. I not to mention my friends were examining the good solutions located on the blog and so before long got an awful suspicion I never expressed respect to the site owner for those secrets. Most of the young boys had been absolutely stimulated to read all of them and have quite simply been tapping into these things. Appreciate your turning out to be simply considerate as well as for finding this form of brilliant topics most people are really eager to be aware of. My personal sincere apologies for not expressing gratitude to you sooner.

  11. Hi, I do think this is an excellent web site. I stumbledupon it 😉 I will come back once again since i have saved as a favorite it. Money and freedom is the greatest way to change, may you be rich and continue to help others.

  12. I am commenting to make you understand of the extraordinary experience my friend’s child gained studying your site. She noticed numerous things, not to mention what it’s like to possess a marvelous teaching nature to let many more with no trouble gain knowledge of specific specialized issues. You undoubtedly did more than visitors’ expected results. Thank you for delivering these effective, safe, edifying and also cool thoughts on the topic to Jane.

  13. Wazzup Fellow Writer, What you ?have here really have me interested up to the last word, and I wanna say to you I am not that typical man who finish the full length post of blogs as I most of the time got bored and tired of the trash content that is presented to me on a daily basis and I simply end up checking out the pics and maybe a headline, a paragraph and so on. But your headline and the first paragraphs were so cool and it right on the spot got me hooked. Thanks for tearing me out of this boring world! Thanks, really.

  14. I wish to express my admiration for your generosity giving support to men and women that actually need assistance with this important subject matter. Your very own dedication to getting the message all through turned out to be remarkably useful and have without exception encouraged women much like me to arrive at their targets. Your new important suggestions means much a person like me and a whole lot more to my office workers. Thank you; from all of us.

  15. Needed to post you a bit of word to thank you as before about the extraordinary techniques you’ve shown at this time. It is simply particularly open-handed with people like you giving openly what many people could have offered as an electronic book in making some money for their own end, particularly since you might have tried it in case you wanted. These solutions additionally acted to be a fantastic way to be aware that other individuals have the identical fervor really like mine to know great deal more with reference to this problem. Certainly there are thousands of more pleasant opportunities ahead for many who look over your website.

  16. Good post. I learn something totally new and challenging on sites I stumbleupon everyday. It’s always helpful to read articles from other authors and practice a little something from their websites.

  17. Thanks so much for providing individuals with an exceptionally splendid opportunity to read from this site. It really is so lovely and as well , packed with a great time for me and my office co-workers to search your site on the least thrice per week to see the latest tips you have. Of course, I am always pleased considering the good methods served by you. Some 1 ideas in this posting are truly the best I have had.

  18. I simply needed to appreciate you again. I’m not certain the things that I could possibly have created without the entire suggestions revealed by you concerning such industry. This has been an absolute difficult problem in my position, however , noticing the very specialised style you dealt with that took me to jump for contentment. I will be thankful for your service as well as pray you know what a powerful job you are always putting in instructing people via a site. Most likely you’ve never come across any of us.

  19. My husband and i were quite thrilled when Ervin managed to round up his preliminary research using the ideas he received out of the web pages. It’s not at all simplistic just to happen to be freely giving facts people today may have been making money from. Therefore we already know we now have the blog owner to be grateful to for that. The type of explanations you have made, the easy web site navigation, the friendships you can aid to create – it’s many incredible, and it is helping our son and our family believe that this idea is fun, which is quite vital. Thank you for the whole thing!

  20. I am just commenting to make you understand what a beneficial experience my cousin’s girl gained using yuor web blog. She learned a lot of things, with the inclusion of what it is like to have an awesome teaching spirit to let folks clearly have an understanding of a number of very confusing things. You actually exceeded visitors’ desires. Thanks for offering the useful, dependable, revealing and in addition unique thoughts on your topic to Emily.

  21. Thanks so much for providing individuals with such a marvellous possiblity to discover important secrets from this site. It’s usually very terrific and also jam-packed with fun for me and my office friends to visit your blog a minimum of 3 times every week to see the newest things you have. And lastly, I’m always happy with all the astounding thoughts you serve. Selected 2 facts on this page are definitely the very best I’ve ever had.

  22. That is a great tip especially to those new to the blogosphere. Simple but very precise information… Thank you for sharing this one. A must read post.

  23. I and my friends were found to be looking through the excellent techniques found on your web blog and then got a terrible suspicion I never expressed respect to you for those secrets. These people ended up consequently very interested to read all of them and have really been tapping into these things. Thank you for being really kind as well as for deciding on this form of helpful subject areas most people are really desirous to discover. My very own honest apologies for not expressing appreciation to you sooner.

  24. Hi, I do think this is an excellent blog. I stumbledupon it 😉 I may return yet again since I book marked it. Money and freedom is the best way to change, may you be rich and continue to guide other people.

  25. I and my buddies were studying the great key points found on your web page and suddenly got a terrible suspicion I never expressed respect to the site owner for them. Those ladies happened to be for this reason passionate to read through all of them and have in effect in fact been having fun with those things. I appreciate you for turning out to be simply accommodating and also for choosing this kind of decent things most people are really needing to understand about. My personal sincere apologies for not expressing gratitude to sooner.

  26. My wife and i felt comfortable when John managed to deal with his investigations with the precious recommendations he got from your very own web pages. It’s not at all simplistic to simply continually be handing out steps that men and women might have been making money from. And we also fully grasp we have you to appreciate for this. Those illustrations you made, the straightforward blog navigation, the friendships you assist to engender – it is all wonderful, and it’s really helping our son and us do think the subject matter is enjoyable, which is very important. Many thanks for the whole lot!

  27. My spouse and i got quite fulfilled Emmanuel managed to conclude his basic research by way of the ideas he made in your web pages. It is now and again perplexing to simply be giving for free things which some other people could have been making money from. Therefore we fully grasp we have the website owner to appreciate for that. These illustrations you have made, the simple web site menu, the relationships you can assist to instill – it’s all great, and it’s really facilitating our son in addition to us reason why the matter is pleasurable, which is rather important. Thanks for the whole thing!

  28. I am only commenting to make you be aware of what a beneficial encounter my princess developed using your web page. She realized many pieces, with the inclusion of what it’s like to have an amazing giving mindset to let most people without hassle completely grasp selected very confusing things. You actually did more than my expectations. Many thanks for giving the practical, trustworthy, edifying and even cool tips about that topic to Sandra.

  29. I simply had to say thanks once more. I am not sure what I would have used in the absence of the actual solutions revealed by you about such a subject. Entirely was a real horrifying circumstance in my circumstances, but taking a look at this professional avenue you managed that forced me to cry for contentment. I’m just grateful for your information and as well , expect you realize what an amazing job you are providing instructing men and women using your web page. Most probably you haven’t come across any of us.

  30. The next time I read a blog, Hopefully it does not disappoint me just as much as this particular one. I mean, Yes, it was my choice to read, but I genuinely thought you would probably have something interesting to talk about. All I hear is a bunch of crying about something you could possibly fix if you weren’t too busy searching for attention.

  31. Thank you a lot for providing individuals with an extremely marvellous possiblity to discover important secrets from here. It can be so great and as well , jam-packed with a great time for me personally and my office mates to visit your blog at minimum three times in a week to read the new secrets you will have. And definitely, I am actually happy for the astounding concepts served by you. Some two areas on this page are clearly the most impressive we’ve had.

  32. An interesting discussion is worth comment. I do believe that you need to publish more on this issue, it might not be a taboo matter but generally people don’t talk about such topics. To the next! Best wishes!

  33. I wish to show my love for your generosity in support of folks that must have guidance on in this field. Your personal commitment to getting the message across ended up being exceptionally helpful and has without exception permitted many people just like me to arrive at their pursuits. Your own warm and helpful help and advice means a whole lot a person like me and far more to my office workers. Many thanks; from each one of us.

  34. My wife and i got quite happy Peter could finish off his inquiry from the ideas he was given when using the web page. It’s not at all simplistic just to always be offering solutions which usually others may have been trying to sell. We really do understand we’ve got the blog owner to give thanks to because of that. Most of the illustrations you’ve made, the easy site menu, the relationships you make it possible to instill – it’s got all powerful, and it’s really assisting our son in addition to the family feel that that matter is excellent, and that’s wonderfully important. Thanks for the whole thing!

  35. I am also commenting to let you understand of the wonderful encounter my wife’s princess gained visiting your webblog. She even learned a wide variety of details, not to mention what it is like to have a marvelous coaching mood to make certain people smoothly learn a number of multifaceted things. You really did more than my desires. Thank you for displaying these essential, dependable, educational and easy thoughts on the topic to Tanya.

  36. I simply desired to say thanks again. I am not sure the things that I could possibly have gone through without the opinions provided by you regarding such industry. It was a real distressing dilemma in my position, but considering the very skilled fashion you resolved that took me to weep with gladness. I am grateful for the support and even pray you are aware of a powerful job you are always doing educating the others through your blog. More than likely you haven’t encountered all of us.

  37. Hi there! This post couldn’t be written any better! Looking through this article reminds me of my previous roommate! He always kept talking about this. I’ll forward this information to him. Fairly certain he will have a good read. Many thanks for sharing!

  38. I definitely wanted to send a simple remark in order to express gratitude to you for the fantastic hints you are giving out on this site. My time intensive internet investigation has now been recognized with useful details to write about with my colleagues. I ‘d repeat that most of us readers actually are extremely endowed to exist in a very good community with many marvellous professionals with useful ideas. I feel very grateful to have discovered the site and look forward to so many more pleasurable times reading here. Thank you once again for a lot of things.

发表评论

电子邮件地址不会被公开。 必填项已用*标注