Novice learns Django's 10 note points

Source: Internet
Author: User
Just beginning to learn Django Novice note, here summed up 10 points of attention, can help you better learn Django, reduce errors, avoid detours, it is worth a look oh ~ ~

1, do not include the project name in the reference code
For example, if you create a project called "Project" that contains an app called "app," the following code is not good:

From Project.app.models import Author

The downside is that applications and projects become tightly coupled and cannot easily be reused. If you want to change the name of a project in the future, you will have to suffer.
The recommended practice is to:

From App.models import Author

Note that you need to configure the path of the project in Pythonpath.
2, do not hard code 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/"

A problem occurs when you deploy to a production environment, or migrate a server.
It is recommended to use the following methods:

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, 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 the static file in the template
When linking Css,javascript or pictures in a 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>

When your project needs to provide static files to other servers, it will usually be a different HTTP address, then you have to replace all the/appmedia/with a new address, the site to write code is already boring enough.
The workaround for no worries is to use {{Media_url}} instead of a 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>

How does a template context variable get to it? Please use RequestContext to:

Return Render_to_response ("app/template.html", {' var ': ' foo '},  Context_instance=requestcontext (Request))

Information such as current user can also be obtained from RequestContext.

4, do not write business logic code into the view

Don't confuse, although you may have read a lot of books and examples, they have written the logic in the views.py, but please do not do so. Because it is not conducive to unit testing, it is not conducive to reusing code.
Where should I put my business logic? It is recommended to put in a model or create an auxiliary (helper) module separately.
Of course, from the model to get a author, get the author list of the code can be put into the view.
5. Don't forget to set debug to False when deploying
We often forget to disable debug at deployment time, there are many ways to handle this configuration automatically:

Import Socket  if socket.gethostname () = = ' productionserver.com ':     debug = falseelse:     debug = True

Another way is to use a different configuration file:

#文件名: settings_debuy.py# contains configuration information for debug mode #http://www.pythontab.com# using Python manage.py runserver settings=settings_ debug.py to run the project from settings import *debug = true# You can also configure more variables to use when debugging:)

6, load a custom template label only once
When you need to use custom or third-party template tags and template filters, you typically use them in templates:

{% load template_tags%}

The reality is that you need to use the above code in all templates that use custom template tags and template filters, so it's not dry.

From Django Import Template Template.add_to_builtins (' App.templatetags.custom_tag_module ')

Please put the above code in the module that can be loaded when the project starts (settings.py, urls.py, models.py, etc.).

The purpose of the above code is to load the custom template tags or filters at the start of the project, which can be used anywhere in the template, without the need for {% load template_tags%}.
7, reasonable configuration and use of URLs
Do not configure the URLs in a 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"),,)

The recommended approach is to configure the URL of each app in its own urls.py, which makes it easier for applications to reuse into different projects:

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 application of the Askalumini urls.py:

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"))

Just mentioned the static file path do not hard code, URL processing method also try not to hard code, otherwise when you change an address will involve many changes, you can use some URL function to handle.

In/project/askalumini/urls.py, name is defined for each URL, which helps us to effectively work with URLs in views, templates, and models, rather than hard coding.
To ensure that the name is unique, follow the customary usage of naming the URL <appname>/<somelabel>.
For example, the following code is in the views.py file :

Httpresponseredirect ("/ASKALUMINI/QUESTIONS/54")

Please instead:

From django.core.urlresolvers Import Reverse httpresponseredirect (reverse (' askquestiondisplay ', kwargs={' Questionno ': q.id}))

Use the Models.permalink adorner in the model to format the URL:

@models. Permalink def get_absolute_url (self): return (' Profileurl2 ', (), {' UserID ': self.user.id})

Use URL tags instead of hard-coded in templates:

{% URL askquestiondisplay 345%} <a href= "{% URL askquestiondisplay 345%}" > Ask Question </a>

8, commissioning
Debugging typically uses some third-party tools to get more run-time information.
How many sentences of SQL does a request execute? How long did it take?
Which template is called? What cookies are set by the client? What about the session?
You can use Django-debug-toolbar to view the above and even more information
Another tool is Werkzeug debugger, which opens the Python shell on the error page, making it easier for you to track error messages
And the PDB, a powerful debugging tool: http://ericholscher.com/blog/2008/aug/31/using-pdb-python-debugger-django-debugging-series-/
9, learn Pinax spare
The biggest advantage of Django is code reuse, Dry,pinax is a platform that contains many code that can be used directly, such as OpenID, email validation, and so on. Please visit: http://pinaxproject.com/
10. Learn about some useful third-party applications
1) Database Upgrade tool
What is the database upgrade tool? You run the syncdb, and after a year of running, you change the model, add fields, delete fields, and run syncdb again? Or alter TABLE ...?
Django-evolutions can help you do the things above, but it doesn't seem strong enough: http://code.google.com/p/django-evolution/
South can be very strong to do the above things, but need to learn how to use: http://south.aeracode.org/
2) Template system
Django's own template system can be replaced, and each has its own pros and cons.
Template-utils enhances the functionality of template comparison labels, and provides some other practical features
Jinja is a complete third-party templating system that can replace the default template system, which provides a number of superior features
3) third-party applications
The Django Command extensions provides a number of practical functions:
Shell_plus Load all Django models
Runserver_plus integrates the Werkzeug debugging tools
Generate a model diagram that you can show to your boss
......

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.