Django web programming ideas
Global Setting
- Generate a project
- Initialize settings. py
- Generate application module app
- Install the app to the Project
APP setting
- Compile models. py
- Define URLs. py
- Add app URLs to project URLs Configuration
- Write views. py
- Compile the corresponding Template
Run Server
- Start the project and access
Check Environment
- Python2.6
- Django http: // www.djangoproject.com/download
- Config pythonpath/etc/environment
Start Project
$django-admin.py startproject mysite
Generate project files
The Manage. py file is basically a copy of The django-admin.py, but added to check whether the current directory settings. py file exists, does not exist, exit.
Settings. PY: This file extracts the information from the Django/CONF/global_settings.py file, and finally Django. conf. the settings module merges all settings of the current project and global_settings. If the same settings name exists, the settings of the previous project prevails,Note: all the letters of the Set name must be in upper case. Django only specifies the upper case, otherwise it will turn a blind eye.
URLs. py: Responsible for URL parsing and allocation. The regular expression is used to match the URL, so as to determine which page display function should be called for display and what function parameters are.
URL controller URLs. py
Then we are modifying URLs. add a line (R' ^ $ ', 'Views. index'), in which the regular expression '^ $ 'indicates matching an empty string. No space can be added, because ^ ends at the beginning $!
Then, 'Views. Index' is followed to call the index function of the Views module.
Note:
- By default, any request URL that does not match or does not have a slash (/) at the end will be redirected to a URL with the same words at the end of the slash. (This is controlled by the append_slash item in the setting configuration file)
- Django removes the slash (/) at the beginning of each requested URL before checking the URL mode (/). This means that the/Hello/Write URL mode does not contain a slash (/).
- Note that the hello view function is passed as an object rather than called. This is an important feature of Python (and other dynamic languages): functions are first-class objects, which means you can pass them like other variables.
- Another important point is that the regular expression string starts with the letter "R ". It tells Python that this is a raw string and does not need to process the backslash (Escape Character) in it)
View File views. py
Views. the view function defined in Py must have at least one parameter, and the first parameter must be set to Django/HTTP/_ init __. the subclass of the class httprequest defined in Py is not necessarily the subclass. This type of function must return a result of the httpresponse type.
Template
Syntax description:
Template tag for output variables {var}
{% If bool %} block tag
{Var_date | date, 'fj, y'} filter (** convert the output format of variables. The filter is called using the pipe operator (| **), ship date is converted by MPs queue. The date type is defined later.
Once you create a template object, you can use context to pass data to it. A context is a collection of variables and their values. Call the render () method of the template object and pass context to fill the template.
This is the basic rule for using the Django template system: Write a template, create a template object, create a context, and call the render () method.
Search for deep variables:
The template system can easily process more complex data structures, such as list, dictionary, and custom objects. _ The key to traversing complex data structures in the Django template is the period (.)__.
If the template specified by the {% include %} tag is not found, Django selects one of the following two processing methods:
- If debug is set to true, a templatedoesnotexist exception is displayed on the Django error message page.
- If debug is set to false, this tag will not cause an error and will not display anything at the tag position.
Data Model models. py
This is used to write data models for Django's built-in object-oriented database. The data model can generate corresponding physical database tables through the syncdb command.
Start Project
$python manage.py runserver 0.0.0.0:8000
Access: http: // localhost: 8000/
Start app
$django-admin.py startapp appname
A project can contain multiple modules. Django regards each module as an app. Different app modules focus on different services, and each app has a large programIndependence, Can be implemented wellCode reuse.
Generate Application Files
- Models. py: used to write data models for Django's built-in object-oriented database. The data model can generate corresponding physical database tables through the syncdb command.
- Views. py: used for page display or Page Control
Generate data table
$python manage.py syncdb
Map all model definitions in the project to the data table, that is, the ORM: Object Relational Model syncdb command is a simple method to synchronize your model to the database. It checks the database based on the app set in installed_apps. If the table does not exist, it creates it. Note that syncdb cannot modify or delete a model to the database. If you modify or delete a model and want to submit it to the database, syncdb does not perform any processing.
$python manage.py app info
View the data table to be generated
$python manage.py validate
The validate command checks whether the syntax and logic of your model are correct. If everything is normal, you will see the 0 errors found message. If an error occurs, check the model code you entered. The error output provides useful error information to help you correct your model.
$python manage.py sqlall app
Outputs the SQL information of the model data table created under an app, and does not actually create the data table name: app_model
Note:
- To automatically map the data model defined by the application to the database, you must install the corresponding application in installed_apps in settings. py.
- Django automatically adds an id Primary Key for each table. You can reset it.
- Follow the conventions to add the "_ id" suffix to the field name of the foreign key. You guessed it. This is also customizable.
- Foreign keys are clearly defined using the references statement.
Django Problem Solving
1. Django environment variable settings
PATH = ${django_home}/bin;
PYTHONPATH = ${django_project_path}
DJANGO_SETTINGS_MODULE = mysite.settings
Mysite is the project name
Django Python Shell
$python manage.py shell
Go to the shell with Django configuration. You can tell Django which setting file to use without setting the Django environment variable before starting the interpreter.
Most subsystems of the Django framework, including the template system, depend on the configuration file. If Django does not know which configuration file to use, these systems will not work.
Principle: Django searches for the environment variable django_settings_module, Which is set in settings. py. When manage. py is run, it automatically loads settings. py.
Character encoding
T. Render (c) returns a unicode object, not a common Python string. You can use the u before the string to distinguish.
In the Framework, Django will always use Unicode objects instead of common strings. Index of Negative List is not allowed in template. Template variables such as {items.-1} will cause ''templatesyntaxerror''
The period search rules can be summarized as follows:
- Dictionary type search (for example, foo ["bar"])
- Attribute search (such as Foo. Bar)
- A method call (such as Foo. Bar () is valid only when a method does not require parameter input. Otherwise, the system will move to the next search type (List index search ).
- List-type index search (for example, foo [bar])
- The template system does not perform any marking method in this way. In the following example, if the template file contains {account. delete}, the object has the delete () method again, and delete () has the alters_data = true attribute, the delete () method will not be executed when the template is loaded. It will quietly exit by mistake.
Invalid Variable Processing
By default, if a variable does not exist, the template System displays it as a null string and does nothing to indicate failure.
The template system does not perform any marking method in this way.
In the following example, if the template file contains {account. delete}, the object has the delete () method again, and delete () has the alters_data = true attribute, the delete () method will not be executed when the template is loaded. It will quietly exit by mistake.
Django MVC
Django closely follows this MVC pattern, which can be called an MVC framework. The meanings of M, V, and C in Django are as follows:
- M, data access part, processed by the Django database layer
- V. The view and template process the data to be displayed and the data to be displayed.
- C. According to the user input, the Django Framework calls the appropriate Python function for the given URL Based on the urlconf settings. Since C is handled by the framework itself, Django focuses more on models, templates, and views. ** Django is also called the MTV framework.
To sum up
- Incoming Request Transfer/Hello /.
- Django decides the root urlconf by configuring root_urlconf.
- In all URL modes in urlconf, Django finds the first entry that matches/Hello.
- If a match is found, the corresponding view function is called.
- The view function returns an httpresponse
- Django converts httpresponse to an appropriate HTTP response, which is displayed on the web page.