"First day" Django rapid development-environment deployment, forms, database operations, templates, file learning

Source: Internet
Author: User
Tags inheritance install django

Installing Django

1, installation Setuptools

Yum Install Python-setuptools

2. After completion, you can use the Easy_install command to install Django

Easy_install Django


Note: Django has strict requirements for PIP and setuptools versions, so if you don't want to be bothered, suggest a python3.6.


Django Admin Commands

django-admin.py

This is the Django Admin command, which can be used to manipulate project or app in any directory.

The most commonly used commands are summarized as follows:

1. Create a project

Django-admin Startproject [Name]

2. Create an App

Django-admin Startapp [Name]

Concepts for Project and app:

In Django, a project covers a number of apps that are used to enable reusable functionality. This makes it possible to invoke this app when I want to use a function that has been implemented.

manage.py

This command is used to start the UWSGI service for a project with the following command:

Python manage.py runserver 0.0.0.0:8000

What is UWSGI?

UWSGI is a Web server that implements protocols such as WSGI Protocol, UWSGI, HTTP, and so on. The role of Httpuwsgimodule in Nginx is to exchange with the UWSGI server. WSGI is a Web server gateway interface. It is a specification of a Web server (such as a server such as NGINX,UWSGI) that communicates with a Web application, such as a program written with the Flask framework.


Django File Introduction

About the urls.py file

This file is used to define the view information that can be displayed. The relevant code is as follows:

The above information I put some of my own code up

URL () Introduction

This function is used to point to the routing information, url (A, b.c.[d]). Where the A uses the regular expression to represent the route name, such as the URL in (R ' ^search ' ..... Indicates access to the URL can be accessed via 127.0.0.0:8000/search. In a regular expression, ^ represents a line that begins with search, and $ represents a line that ends with search.

where d, is an option that represents name. Simply put, name can be used in templates, models, views ... Get the corresponding URL, equivalent to "give a name to the URL", as long as the name is not changed, the URL can also be obtained by name.

The b represents the Python file you wrote, and C represents the function in your Python file.


Attention

After you start Django, you cannot access it and report a 400 error.

Reason: Allow access is not turned on

Processing: Edit HelloWorld directory under setting.py, put one of the

Allowed_hosts=[] Change to allowed_hosts=[' * ' ##* means any address.


Django templates

Templates are an important part of Django's idea of implementing MVC

How to use a template

1. Defining variables in the HTML front-end file

2. Define the path to the template file in settings.py

Modify helloworld/helloworld/settings.py

3. Modify the view.py file to add a new object to submit the data to the template

view.py are self-defined, not system-generated

About the render () method

Once you create a Template object, you can use the context to pass the data to it. A context is a collection of variables and their values. The hello.html represents the target object for the value transfer. The request is a fixed parameter that represents the transfer in Request mode.

4. The key value "Hello" of the element in the context dictionary corresponds to the variable "{{Hello}}" in the template. Re-access access to Http://127.0.0.1:8000/hello, you can see the page


Template label

1. Judgment

{% if%} tags accept and, or or not keyword to make judgments on multiple variables, or to negate variables (not)

(1)

{% if condition%} ... display{% endif%}

(2)

{% if Condition1%} ... display 1{% elif condition2%} ... display 2{% else%} ... display 3{% endif%}


2. Circulation

For example, given an athlete list athlete_list variable, we can use the following code to display this list

<ul>{% for athlete in athlete_list%} <li>{{athlete.name}}</li>{% endfor%}</ul>

Reverse Iteration

{% for athlete in athlete_list reversed%} ... {% ENDFOR%}

Nesting

{% for athlete in athlete_list%} 


3. Ifequal/ifnotequal Label

Compares two values, showing all values in {% ifequal%} and {% endifequal%} when they are equal.

{% ifequal user CurrentUser%} 


4. Comments

{# This is a comment #}


5. Filter

The template filter can modify the variable before it is displayed, and the filter uses the pipe character

Converts the first element in a my_list to uppercase

{{My_list|first|upper}}

Show only the start of the Bio parameter 30 elements

{{bio|truncatewords: ' 30 '}}


6. Include tags

The {% include%} tag allows the contents of other templates to be included in the template.

{% include "nav.html"%}


Template inheritance

1. Create a template file html

The tag used for inheritance is Mainbody, and the successor can replace the part. The block tag is used to tell the template engine that the Purple MO version can reload these parts.

2, hello.html inherit base.html, and replace the specific block. Where you specify the extends label to specify the parent file.


manipulating databases

Django's operation of the database I think is the most troublesome, for this I still prefer to import a library in flask and then through the SQL query method. It's a hassle, but it can support many databases including PostgreSQL, MySQL, SQLite, Oracle, so it's a good thing to see.

Environment preparation

1. Installation drive

First you need to install the database driver, MySQL for example need to install Mysqlclient

python3-m pip Install Mysqlclient

2. Configuring the settings.py File

3. Create an App

Django rules that if you want to use a model, you have to create an app. We use the following command to create a Testmodel app

django-admin.py Startapp Testmodel (inside the project folder)

After that, a Testmodel folder will appear.

helloworld|--testmodel|   |--__init__.py|   |--admin.py|   |--models.py|   |--tests.py| '--views.py

The models file is used primarily to define information for modeled files. We modify this file

Where test represents the table name of the database, name represents the column name, Charfield is similar to the varchar type, and max_length represents a maximum length of 20 bytes.

4. Add app to settings.py

5. Change of application Template

Then enter a command to apply the changes defined in the app

$ python manage.py Migrate # CREATE TABLE structure $ python manage.py makemigrations Testmodel # Let Django know we have some changes in our model $ python Manage . py Migrate Testmodel # CREATE TABLE structure

Your data sheet is ready to be created.


Inserting data

1. Add a python working file such as testdb.py

Inserting data using

Test1 = Test (name= ' Runoob ') Test1.save ()

2. Define urls.py

Data query

Summary of data query methods

1, the use of filters, equivalent to where

Test.objects.filter (id=1)

2. Get a single object, equivalent to where

Test.objects.get (id=1)

3, sort, equivalent to the order

Test.objects.order_by ("id") can be chained using Test.objects.filter (name= "Runoob"). Order_by ("id")

4. Get all data, equivalent to select * FROM

List = Test.objects.all ()

Change data

Change data using Save (), or update ()


Delete data

Call Delete () to



Django Processing a form

HTML forms are an important technique for front-end interaction


Get method

1, the front-end definition of the form, using the Get method, the following is search_form.html

2, wearing a Python working file search.py (name not all)

Use request. Get method gets the data passed by the front end

3. Define Routes

Slightly


Post method

1, create the front-end file, note that the Post method must use the Csrf_token tag. CSRF full name is cross Site Request forgery. This is the functionality Django provides to prevent spoofing submission requests. The POST method submits a table that must have this label.

RLT label indicates the processing result reserved location for table processing

2. Create a Python file to process the form request

Attention

Execute search Request response, an error occurred, Chinese cannot parse:

' ASCII ' codec can ' t decode byte 0xe4 in position 0:ordinal not in range (128)

Workaround, add the following code to search.py

Import sys reload (SYS) sys.setdefaultencoding (' UTF8 ')


"First day" Django rapid development-environment deployment, forms, database operations, templates, file learning

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.