Ten points for beginners to pay attention to when learning Django

高洛峰
Release: 2016-10-17 14:40:10
Original
988 people have browsed it

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
Copy after login

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
Copy after login

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/"
Copy after login

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'),)
Copy after login

(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>
Copy after login

When your project needs to provide static files from other servers, Usually it will be another http address, then you have to replace all /appmedia/ with the new address. Writing code for a website is tedious enough.

The worry-free solution is to use {{ MEDIA_URL }} instead of the hard-coded path:

<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}amazing.css" />
    <script type="text/javascript" src="{{ MEDIA_URL }}jquery.min.js"></script>
Copy after login

How to obtain the template context variable? Please use RequestContext:

return render_to_response("app/template.html", {&#39;var&#39;: &#39;foo&#39;},  context_instance=RequestContext(request))
Copy after login

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() == &#39;productionserver.com&#39;: 
    DEBUG = False
else: 
    DEBUG = True
Copy after login

Another way is to use different configuration files:

#文件名:settings_debuy.py
#包含调试模式的配置信息
#http://www.pythontab.com
#使用python manage.py runserver settings=settings_debug.py来运行项目
from settings import *
DEBUG = True
#还可以配置更多在调试时使用的变量:)
Copy after login

6. Only load custom template tags once

When you need to use custom or third-party template tags and template filters, they are usually used in the template:

{% load template_tags %}
Copy after login

The actual situation is that they need to be used in all Use the above code in the templates of custom template tags and template filters, so it is not DRY.

from django import template 
template.add_to_builtins(&#39;app.templatetags.custom_tag_module&#39;)
Copy after login

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(&#39;&#39;, 
  url(r&#39;^askalumini/question/$&#39;,&#39;.....registerInstitution&#39;,name=&#39;iregister&#39;), 
  url(r&#39;^askalumin/answer/$&#39;,&#39;someview.....&#39;,name=&#39;newmemberurl&#39;), 
  url(r&#39;^institution/member/$&#39;,&#39;someview.....&#39;,name="dashboardurl"), 
  url(r&#39;^institution/faculty/$&#39;,&#39;editInstitute&#39;,name="editinstituteurl"), 
  url(r&#39;^memeber/editprofile/$&#39;,&#39;editProfile&#39;,name="editprofileurl"), 
  url(r&#39;^member/changepassword/$&#39;,&#39;changePassword&#39;,name="changepasswordurl"), 
  url(r&#39;^member/forgotpassword/$&#39;,&#39;forgotPassword&#39;,name="forgotpasswordurl"), 
  url(r&#39;^member/changepicture/$&#39;,&#39;changePicture&#39;,name="changepictureurl"), 
  url(r&#39;^member/logout/$&#39;,&#39;memeberlogout&#39;,name="logouturl"), , 
)
Copy after login

The recommended way is to configure the URLs of each application in their own urls.py, so that The application is easier to reuse in different projects:

urlpatterns = patterns(&#39;&#39;, 
  (r&#39;^$&#39;, include(&#39;institution.urls&#39;)), 
  (r&#39;^institution/&#39;, include(&#39;institution.urls&#39;)), 
  (r&#39;^askalumini/&#39;, include(&#39;askalumini.urls&#39;)), 
  (r&#39;^member/&#39;, include(&#39;member.urls&#39;)), 
)
Copy after login

The following is the urls.py of the askalumini application:

urlpatterns = patterns(&#39;askalumini.views&#39;, 
  url(r&#39;^$&#39;,&#39;askHome&#39;,name=&#39;askaluminiurl&#39;), 
  url(r&#39;^questions/(?P<questionno>\d+)/$&#39;,&#39;displayQuestion&#39;,name=&#39;askquestiondisplay&#39;), 
  url(r&#39;^askquestions/$&#39;,&#39;askQuestion&#39;,name=&#39;askquestionurl&#39;), 
  url(r&#39;^postcomment/$&#39;,&#39;postComment&#39;,name="askquestioncomment") 
)
Copy after login

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")
Copy after login
Please change it to:

from django.core.urlresolvers import reverse 
HttpResponseRedirect(reverse(&#39;askquestiondisplay&#39;,kwargs={&#39;questionno&#39;:q.id}))
Copy after login

Use the models.permalink decorator in the model to format the url:

@models.permalink 
def get_absolute_url(self): 
return (&#39;profileurl2&#39;,(),{&#39;userid&#39;: self.user.id})
Copy after login

Use the url tag in the template instead Hardcoded:

{% url askquestiondisplay 345 %} 
<a href="{% url askquestiondisplay 345 %}"> Ask Question </a>
Copy after login

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调试工具
生成模型图表,你可以展示给你的老板
…… 

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template