) 10 important points for beginners of Django

Source: Internet
Author: User

Since last month, it has not been long for me to learn python, but I oftenCommunityLook at what someone else postedArticleI saw a good blog in the morning, but I was unable to access it. I finally found it from the Bing cache. I was afraid of losing or forgetting it. So I translated it and put it here, at the same time, I would like to share with you and contribute to new Django beginners. I hope to help you with the following :)


Original address: http://zeroandone.posterous.com/top-10-tips-to-a-new-django-developer

1. do not include the project name in referenceCodeLi

For example, if you create a project named "project" and contain an application named "app", the following code is not good:

Python code

    1. From project. App. Models import author

Disadvantages: applications and projects become tightly coupled and cannot be easily reused. If you want to change the project name in the future, you may have to accept it.

The Recommended Practice is:

Python code

    1. From app. Models import author

Note that you need to configure the project path in pythonpath.

2. Do not hard encode media_root and template_dirs.

Do not use the following code in the settings. py project configuration file:

Python code

    1. Template_dirs = ("/home/html/project/templates ",)
    2. Media_root = "/home/html/project/appmedia /"

Problems may occur when you deploy the service to a production environment or migrate servers.

The following method is recommended:

Python code

    1. Site_root = OS. Path. realpath (OS. Path. dirname (_ file __))
    2. Media_root = OS. Path. Join (site_root, 'appmedia ')
    3. Template_dirs = (OS. Path. Join (site_root, 'templates '),)

(You can also use abspath, the difference with realpath please refer to the http://rob.cogit8.org/blog/2009/May/05/django-and-relativity-updated)

3. Do not hard encode the path of the static file in the template.

The following method is not recommended when linking CSS, JavaScript, or images in the template:

HTML code

    1. <LINK rel = "stylesheet" type = "text/CSS" href = "/appmedia/amazing.css"/>
    2. <SCRIPT type = "text/JavaScript" src = "/appmedia/jquery. Min. js"> </SCRIPT>

When your project needs to provide static files with other servers, it usually has another HTTP address, so you have to replace all/appmedia/with a new address, it is boring to write code for websites.

The solution without any worries is to use {media_url} instead of the hard-coded path:

HTML code

    1. <LINK rel = "stylesheet" type = "text/CSS" href = "{media_url }}amazing.css"/>
    2. <SCRIPT type = "text/JavaScript" src = "{media_url} jquery. Min. js"> </SCRIPT>

How can I obtain template context variables? Use requestcontext:

Python code

    1. Return render_to_response ("app/template.html", {'var': 'foo '},
    2. Context_instance = requestcontext (request ))

From requestcontext can also get information such as the current user, for more detailed introduction, see: http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/

4. Do not write the business logic code to the view.

Don't be confused. Although you may have read many books and examples, they write the logic in views. py, please do not do this. This is not conducive to unit testing and code reuse.

Where should I put my business logic? It is recommended to put it in the model or create a helper module separately.

Of course, to get an author from the model, the code for obtaining the author list can be put into the view.

5. Do not forget to set debug to false during deployment.

We often forget to Disable debug during deployment. There are many ways to automatically handle this Configuration:

Python code

    1. Import socket
    2. If socket. gethostname () = 'productionserver. com ':
    3. DEBUG = false
    4. Else:
    5. DEBUG = true

For this method, see: http://nicksergeant.com/blog/django/automatically-setting-debug-your-django-app-based-server-hostname

Another way is to use different configuration files:

Python code

    1. # File name: settings_debuy.py
    2. # Contains debugging mode configuration information
    3. # Run the project using Python manage. py runserver settings = settings_debug.py
    4. From settings import *
    5. DEBUG = true
    6. # You can also configure more variables for debugging :)

For this method, see: http://blog.dpeepul.com/2009/07/02/from-now-you-will-never-forget-to-put-debug-true-in-django-production-environment/

6. Only one custom template tag is loaded.

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

Python code

    1. {% Load template_tags %}

The actual situation is that you need to use the above Code in all templates that use custom template tags and template filters, so that it will not be dry.

Python code

    1. From Django import Template
    2. Template. add_to_builtins ('app. templatetags. custom_tag_module ')

Put the above Code in the module (settings. py, URLs. py, models. py, etc.) that can be loaded when the project is started.

The above code is used to load custom template tags or filters at project startup. They can be used anywhere in the template without {% load template_tags % }.

7. Reasonably configure and use URLs

Do not configure all URLs in oneURL. py filesFor example:

Python code

    1. urlpatterns = patterns ('',
    2. URL (R' ^ askalumini/question/$ ','... registerinstitution ', name = 'iregister'),
    3. URL (R' ^ askalumin/answer/$ ', 'someview...', name = 'newmemberurl'),
    4. URL (R' ^ institution/member/$ ', 'someview...', name = "dashboardurl"),
    5. URL (R' ^ institution/faculty/$ ', 'editder', name = "editinstituteurl"),
    6. URL (R' ^ memeber/editprofile/$ ', 'editprofile', name = "editprofileurl"),
    7. URL (R' ^ Member/changepassword/$ ', 'changepassword', name = "changepasswordurl"),
    8. URL (R' ^ Member/forgotpassword/$ ', 'forgotpassword', name = "forgotpasswordurl"),
    9. URL (R' ^ Member/changepicture/$ ', 'changepicture', name = "changepictureurl"),
    10. URL (R' ^ Member/logout/$ ', 'memeberlogout', name = "logouturl"),
    11. )

The recommended method is to configure the URLs of each application in their respective URLs. py, which makes it easier for applications to reuse in different projects:

Python code

    1. Urlpatterns = patterns ('',
    2. (R' ^ $ ', include ('institution. urls ')),
    3. (R' ^ institution/', include ('institution. urls ')),
    4. (R' ^ askalumini/', include ('askalumini. urls ')),
    5. (R' ^ Member/', include ('member. urls ')),
    6. )

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

Python code

    1. Urlpatterns = patterns ('askalumini. view ',
    2. URL (R' ^ $ ', 'askhome', name = 'askaluminiurl '),
    3. URL (R' ^ questions /(? P <questionno> \ D +)/$ ', 'displayquestion', name = 'askquestiondisplay '),
    4. URL (R' ^ askquestions/$ ', 'askquestion', name = 'askquestionurl '),
    5. URL (R' ^ postcomment/$ ', 'postcomment', name = "askquestioncomment ")
    6. )

As mentioned earlier, static file paths should not be hard-coded, and URL Processing methods should not be hard-coded. Otherwise, multiple modifications will be involved when you change an address, some URL functions can be used for processing.

In/project/askalumini/URLs. py, a name is defined for each URL, which helps us effectively process the URL in views, templates, and models, rather than hard encoding.

To ensure that the name is unique, follow the regular usage of naming the URL as <appname>/<somelabel>.

For example, the following code is available in the Views. py file:

Python code

    1. Httpresponseredirect ("/askalumini/questions/54 ")

Change:

Python code

    1. From Django. Core. urlresolvers import reverse
    2. Httpresponseredirect (reverse ('askquestiondisplay', kwargs = {'questionno': Q. ID }))

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

Python code

    1. @ Models. permalink
    2. Def get_absolute_url (Self ):
    3. Return ('fileurl2 ', (), {'userid': Self. User. ID })

In the template, use URL tags instead of hard encoding:

HTML code

    1. {% URL askquestiondisplay 345%}
    2. <A href = "{% URL askquestiondisplay 345%}"> ask question </a>

8. debugging

Debugging usually uses some third-party tools to obtain more runtime information.

How many SQL statements are executed in a request? How long does it take?

Which template is called? What cookies are set on the client? What about session ?...

You can use Django-debug-toolbar to view the above or even more information: http://github.com/robhudson/django-debug-toolbar

Another tool is werkzeug debugger, which can open the python shell on the error page, making it easier for you to track error information, visit: http://blog.dpeepul.com/2009/07/14/python-shell-right-on-the-django-error-page/ for more information.

There is also PDB, a powerful debugging tool: http://ericholscher.com/blog/2008/aug/31/using-pdb-python-debugger-django-debugging-series -/

9. Learn more about pinax backup

The biggest advantage of Django is code reuse. Dry and pinax are such a platform that contains a lot of code that can be used directly, such as openid and email verification. Please visit: http://pinaxproject.com/

10. Learn about some famous third-party applications

1) Database Upgrade Tool

What is a Database Upgrade tool? You have run syncdb. After a year of operation, you have made changes to the Model, added and Deleted fields. Do you want to run syncdb again? Or alter table ...?

Django-evolutions can help you with the above, but it seems not strong: http://code.google.com/p/django-evolution/

South can do the above thing very strong, but need to learn how to use: http://south.aeracode.org/

2) template System

The built-in template System of Django can be replaced, and each has its own advantages and disadvantages.

Template-utils enhances the template's comparative tag and other functions, and provides some other practical features: http://django-template-utils.googlecode.com/svn/trunk/docs/

Jinja is a complete third-party template system that can replace the default template system, which provides many superior features: http://jinja.pocoo.org/2/

3) third-party applications

Django command extensions provides many practical command line functions:

Shell_plus loads all Django Models

Runserver_plus integrates werkzeug debugging tools

Generate a model chart that you can present to your boss

......

See http://ericholscher.com/blog/2008/sep/12/screencast-django-command-extensions/

Sorl can generate thumbnails: http://code.google.com/p/sorl-thumbnail/

............

--- End ---

In addition, many of the original comments have found that:

    • Replacing httpresponseredirect: http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#redirect with the Redirect of Django. shortcuts
    • Use virtualenv to deploy the Django Project
    • Django project specifications: http://ericholscher.com/projects/django-conventions/project/
    • 2nd and 4th are most likely to happen to new users.
    • Point 6th is not suitable for team collaboration

Link: http://shinyzhu.javaeye.com/blog/593427

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.