search
HomeBackend DevelopmentPython TutorialTen points for beginners to pay attention to when learning Django

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>

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>

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

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

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
#还可以配置更多在调试时使用的变量:)

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 %}

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

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

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;)), 
)

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

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

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

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

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

Statement
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
Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.