


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", {'var': 'foo'}, 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() == 'productionserver.com': 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('app.templatetags.custom_tag_module')
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('', 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 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('', (r'^$', include('institution.urls')), (r'^institution/', include('institution.urls')), (r'^askalumini/', include('askalumini.urls')), (r'^member/', include('member.urls')), )
The following is the urls.py of the askalumini application:
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") )
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('askquestiondisplay',kwargs={'questionno':q.id}))
Use the models.permalink decorator in the model to format the url:
@models.permalink def get_absolute_url(self): return ('profileurl2',(),{'userid': 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调试工具
生成模型图表,你可以展示给你的老板
……

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.

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

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

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 within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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.