Attention newbies who have just started learning Django, here are ten points to note, which can help you learn Django better, reduce mistakes, and avoid detours. It is worth a look~~
1. Do not include the project name In the reference code
For example, if you create a project named "project" and contain an application named "app", then the following code is not good:
from project.app.models import Author
The disadvantage is: application and project become closely related Coupling prevents applications from being easily reusable. If you have to change the project name in the future, you'll have to bear with it.
The recommended approach is:
from app.models import Author
Please note that you need to configure the project path in PYTHONPATH.
2. Do not hardcode MEDIA_ROOT and TEMPLATE_DIRS
Do not use the following code in the project configuration file settings.py:
TEMPLATE_DIRS = ( "/home/html/project/templates",) MEDIA_ROOT = "/home/html/project/appmedia/"
Problems will occur when you deploy to a production environment or migrate servers.
It is recommended to use the following method:
SITE_ROOT = os.path.realpath(os.path.dirname(__file__)) MEDIA_ROOT = os.path.join(SITE_ROOT, 'appmedia') TEMPLATE_DIRS = ( os.path.join(SITE_ROOT, 'templates'),)
(You can also use abspath. For the difference with realpath, please refer to http://rob.cogit8.org/blog/2009/May/05/django-and-relativity-updated/)
3. Do not hard-code the path of static files in the template. When linking CSS, javascript or images in the template, it is not recommended to use the following methods:
<link rel="stylesheet" type="text/css" href="/appmedia/amazing.css" /> <script type="text/javascript" src="/appmedia/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}amazing.css" /> <script type="text/javascript" src="{{ MEDIA_URL }}jquery.min.js"></script>
return render_to_response("app/template.html", {'var': 'foo'}, context_instance=RequestContext(request))
You can also get the current user and other information from RequestContext
4. Don’t write business logic code into the view
Don’t be confused, although you may have read many books and examples. They write all their logic in views.py, but please don't do that. Because this is not conducive to unit testing and code reuse.
So where should my business logic be placed? It is recommended to put it in the model or create a separate helper module.
Of course, to get an Author from the model, the code to get the Author list can be placed in the view.
5. Don’t forget to set DEBUG to False when deploying
We often forget to disable DEBUG during deployment. There are many ways to automatically handle this configuration:
import socket if socket.gethostname() == 'productionserver.com': DEBUG = False else: DEBUG = True
#文件名:settings_debuy.py #包含调试模式的配置信息 #http://www.pythontab.com #使用python manage.py runserver settings=settings_debug.py来运行项目 from settings import * DEBUG = True #还可以配置更多在调试时使用的变量:)
When you need to use custom or third-party template tags and template filters, they are usually used in the template:
{% load template_tags %}
from django import template template.add_to_builtins('app.templatetags.custom_tag_module')
Please put the above code into a module that can be loaded when the project is started (settings.py, urls.py, models.py, etc.).
The function of the above code is to load custom template tags or filters when the project is started. They can be used anywhere in the template without {% load template_tags %}.
7. Properly configure and use URLs
Do not configure all URLs in one urls.py file, such as:
urlpatterns = patterns('', url(r'^askalumini/question/$','.....registerInstitution',name='iregister'), url(r'^askalumin/answer/$','someview.....',name='newmemberurl'), url(r'^institution/member/$','someview.....',name="dashboardurl"), url(r'^institution/faculty/$','editInstitute',name="editinstituteurl"), url(r'^memeber/editprofile/$','editProfile',name="editprofileurl"), url(r'^member/changepassword/$','changePassword',name="changepasswordurl"), url(r'^member/forgotpassword/$','forgotPassword',name="forgotpasswordurl"), url(r'^member/changepicture/$','changePicture',name="changepictureurl"), url(r'^member/logout/$','memeberlogout',name="logouturl"), , )
urlpatterns = patterns('', (r'^$', include('institution.urls')), (r'^institution/', include('institution.urls')), (r'^askalumini/', include('askalumini.urls')), (r'^member/', include('member.urls')), )
The following is the urls.py of the askalumini application:
urlpatterns = patterns('askalumini.views', url(r'^$','askHome',name='askaluminiurl'), url(r'^questions/(?P<questionno>\d+)/$','displayQuestion',name='askquestiondisplay'), url(r'^askquestions/$','askQuestion',name='askquestionurl'), url(r'^postcomment/$','postComment',name="askquestioncomment") )
I just mentioned that the static file path should not be hard-coded, and the URL processing method should also try not to be hard-coded, otherwise when you change a The address will involve many modifications, which can be handled by using some url functions.
In /project/askalumini/urls.py, a name is defined for each URL, which can help us effectively handle URLs in views, templates, and models instead of hard coding.
To ensure the uniqueness of the name, please follow the convention of naming the URL as
For example, there is the following code in the views.py file:
HttpResponseRedirect("/askalumini/questions/54")
from django.core.urlresolvers import reverse HttpResponseRedirect(reverse('askquestiondisplay',kwargs={'questionno':q.id}))
Use the models.permalink decorator in the model to format the url:
@models.permalink def get_absolute_url(self): return ('profileurl2',(),{'userid': self.user.id})
Use the url tag in the template instead Hardcoded:
{% url askquestiondisplay 345 %} <a href="{% url askquestiondisplay 345 %}"> Ask Question </a>
8,调试
调试通常会借助一些第三方工具来获得更多的运行时信息。
一个请求执行了多少句SQL?花了多长时间?
调用的哪个模板?客户端设置了什么COOKIE?SESSION呢?。。。
你可以使用django-debug-toolbar查看上面甚至更多的信息
另一个工具是Werkzeug debugger,它可以在错误页面打开python shell,让你更方便的跟踪错误信息
还有pdb,一个强大的调试工具:http://ericholscher.com/blog/2008/aug/31/using-pdb-python-debugger-django-debugging-series-/
9,了解pinax备用
django最大的优点是代码重用,DRY,pinax就是这样一个平台,包含了许多可拿来直接使用的代码,比如openid,电子邮件验证等等。请访问:http://pinaxproject.com/
10,了解一些有用的第三方应用
1)数据库升级工具
什么是数据库升级工具?你运行了syncdb,运行了一年之后,对模型做了更改,添加了字段,删除了字段,要再运行syncdb吗?或者ALTER TABLE ...?
django-evolutions可以帮你完成上面的事情,但它好像不够强壮:http://code.google.com/p/django-evolution/
South能很强壮地完成上面的事情,但是需要学学怎么用:http://south.aeracode.org/
2)模板系统
django自带的模板系统是可以替换的,并且各自有优缺点。
template-utils增强了模板的比较标签等功能 ,并提供其他的一些实用特性
Jinja是一个完整的第三方模板系统,可以替换默认模板系统,它提供了许多优越的特性
3)第三方应用
django command extensions提供了很多实用的命令行功能:
shell_plus加载所有django模型
runserver_plus整合了Werkzeug调试工具
生成模型图表,你可以展示给你的老板
……