Eight key points to note when using Django

Source: Internet
Author: User

1.InSettings. pyUsed inOS. Path. dirname ()

Common Code:

1 # settings.py2 import os3 PROJECT_DIR = os.path.dirname(__file__)4 STATIC_ROOT = os.path.join(PROJECT_DIR, "static")5 ...6 TEMPLATE_DIRS = (7     os.path.join(PROJECT_DIR, "templates"),8 )

The _ file _ variable indicates the current file, and project_dir obtains the absolute path of the current file. This avoids hard encoding of the file path in settings. py.

 

2.UseLocals ()Passing parameters for the Template

The Python built-in function locals () returns a dictionary that maps the names and values of all local variables.

In actual development, you do not need to write every variable for the template, for example:

return render_to_response(‘template.html‘, {"var1": var1, "var2":var2}, context_instance=RequestContext(request))

The optimized code is as follows:

return render_to_response(‘template.html‘, locals(), context_instance=RequestContext(request))

Extended:

render_dict = locals()render_dict[‘also_needs‘] = "this value"return render_to_response(‘template.html‘, render_dict, context_instance=RequestContext(request))

 

3.During deploymentDebugSetFalse

Automatically processed Execution Code:

import socketif socket.gethostname() == ‘XXX-MOBL‘:    DEBUG = Falseelse:    DEBUG = True

 

4.UseExists ()Function to determine whether data is obtained

Code to reduce performance:

books = Books.objects.filter(author__last_name=‘Brown‘)if books:    # Do something

Or

books = Books.objects.filter(author__last_name=‘Brown‘)if len(books):    # Do something

Execute books = books. Object... When the statement is not connected to the database, the database will be operated only after further judgment.

The exists () function determines that as long as there is data, 1 will be returned, and no model attribute will be loaded or large data will be transferred between DB and app.

Therefore, using the exists function can improve the performance, as shown below:

books = Books.objects.filter(author__last_name=‘Brown‘)if books.exists():    # Do something 

 

5.Rational configuration and useURLs

Do not configure all URLs in (mysite/URLs. in a file, you can configure your own URLs based on different apps. in The py file, one of the advantages of doing so is concise and clear, and it is easy to reuse the app to different projects. The sample code is as follows:

urlpatterns = patterns(‘‘,    url(r‘^polls/‘, include(‘polls.urls‘, namespace="polls")),    url(r‘^admin/‘, include(admin.site.urls)),)

The following code exists in the URL. py file of polls:

from polls import viewsurlpatterns = patterns(‘‘,    url(r‘^$‘, views.index, name=‘index‘),    url(r‘^(?P<poll_id>\d+)/$‘, views.detail, name=‘detail‘),    url(r‘^(?P<poll_id>\d+)/results/$‘, views.results, name=‘results‘),)

For example, if you want to implement the following functions, hard-coded/polls/will cause a lot of trouble in the future.

<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>

The optimized code is as follows:

<li><a href="{% url ‘polls.detail‘ poll.id %}">{{ poll.question }}</a></li>

The {% URL %} tag is based on "polls. detail "in mysite/URLs. find the corresponding URL of namespage = "polls" in The py file, for example, Poll. the ID variable is 5, and the actual code after evolution is as follows:

<Li> <a href = "project root directory/polls/5/" >{{ poll. Question }}</A> </LI>

The other advantage of doing so is to avoidTemplateHard-codedURL, This is alsoDjangoImportant points in programming (do not hard coding in the templateURL)

 

6.Do not hard-code static file paths in the template

Poor code Demonstration:

{{ poll.question }}</img>

Django. contrib. staticfiles is an app for static resource management. There are three settings. py:

Static_root: during project deployment, You need to collect all the static files used (including files in the static folder of each app under installed_apps and files in the staticfiles_dirs setting directory) to a directory, it is handed over to the server for processing (when the project is actually deployed, You need to configure the server to serve this directory). static_root is the directory that is used only when running the collectstatic command.

Static_url: the starting directory of the static file and the address prefix during browser access. If static_url =/test/, after runserver, the path of any static file will start with/test, "/test/" indicates static_root. (You can modify the static_url value at will, but it must start with a slash. Otherwise, the static file address cannot be found ).

Staticfiles_dirs: in addition to the static directory of each app, other static file settings that need to be managed.

 

Optimized Code:

{{ poll.question }}</img>

Or

{% load staticfiles %}

PS:{% Static %}And{Static_url }}To be resolved

 

7.Load custom template labels only once

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

{% load cms_tags %} 

The actual situation is that the above Code must be used in all templates that use custom template tags and template filters.

To dry, the optimized solution is: Add the following code to the file (setting. py, URLs. py, etc.) that can be loaded when the project is started .)

from django import templatetemplate.add_to_builtins(‘cms.templatetags.cms_tags‘)

 

8. Learn about some third-party applications

A. data migration-South

Common commands:

Python manage. py schemamigration youappname-initialpython manage. py schemamigration youappname -- Auto # Check Python manage. py migrate youappnampython manage. py syncdb

B. Django debug -- Django-debug-toolbar (using ing ...)

 

Eight key points to note when using Django

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.