Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

13.django getting started 01 (django getting started View, templates, routing)

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

First, the basic use process of django.

Pip install django # install django

Create a project:

Django-admin startproject mysite

-mysite

-settings.py

-url.py

-wsgi.py

-manage.py (startup file)

Name the project:

Python mannage.py startapp app01

Django-admin.py is a command-line tool for managing tasks in Django. Manage.py is a simple wrapper for django-admin.py. There is a mannage.py in every Django Project.

Build a django project: django-admin.py startproject mysite

The project of mysite will be generated under the current directory. The directory structure is as follows:

Manage.py: a tool in the Django project that allows you to call django shell, databases, and so on.

Settings.py: contains the default settings for the project, including database information, debug flags, and other working variables.

Urls.py: responsible for mapping URL schemas to applications.

Create blog application under mysite directory: python manage.py startapp blog

Attention! Be sure to comment out the 'django.middleware.csrf.CsrfViewMiddleware'' of MIDDLEWARE in the settings.py file!

Start a django project:

Python manage.py runserver 127.0.0.1:8080

So our django starts up! We can see it when we visit: http://127.0.0.1:8080/.

Generate a script to synchronize the database: python manage.py makemigrations

Synchronize database: python manage.py migrate

Note: in the process of development, after the misoperation of database synchronization, you will inevitably encounter the situation that the synchronization is not successful. A simple and rude way to solve this problem is to delete all the scripts (except _ _ init__.py) under the migrations directory, and then delete the database to create a new database, and do the database synchronization operation again.

When we visit http://127.0.0.1:8080/admin/, there is:

So we need to create a super administrator for the background to enter the project: python manage.py createsuperuser, set up the user name and password and then log in!

# admin is a background database management system that comes with Django.

Other actions:

Empty the database: python manage.py flush

Ask for details of a command: django-admin.py help startapp

Launch the interactive interface: python manage.py shell

The difference between this command and running python directly into shell is that you can call API in the models.py of the current project in this shell, and it is very convenient to manipulate data and some small tests.

Enter python manage.py on the terminal to see a detailed list, which is especially useful when you forget child names.

Second, related to the django configuration file.

Connect to the database.

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql'

'NAME':'dbname'

'USER': 'root'

'PASSWORD': 'xxx'

'HOST':''

'PORT':''

}

Because Django internally connects to MySQL using the MySQLdb module, which is not yet available in python3, you need to use pymysql instead.

# in the _ _ init__.py file of the configuration with the same name as project placed with the following settings

Import pymysql

Pymysql.install_as_MySQLdb ()

two。 Configure template path

TEMPLATE_DIRS = (

Os.path.join (BASE_DIR,'templates')

)

3. Configure static file path

STATICFILES_DIRS = (

Os.path.join (BASE_DIR,'static')

)

Third, django's url routing system is related.

URL configuration (URLconf) is like the directory of the website supported by Django. It's essentially a mapping table between the URL schema and the view functions to be called for the URL schema; that's how you tell Django that you call this code for this URL and that code for that URL.

Format:

Urlpatterns = [

Url (regular expressions, views view functions, parameters, aliases)

]

# regular expressions have nothing to explain.

# views view function: a callable object, usually a view function or a string that specifies the path of the view function.

The argument after # is passed to the view function. (in the form of dictionary)

Corresponding to a single route:

Url (r'^ index$', views.index)

Regular-based routing:

Url (r'^ index/ (\ d *)', views.index)

Url (r'^ manage/ (? P\ w*) / (? P\ d *)', views.manage)

Add additional parameters:

Url (r'^ manage/ (? P\ w *)', views.manage, {'id':333})

Set the name for the url route:

Url (r'^ home', views.home, name='h2')

Url (r'^ index/ (\ d *)', views.index, name='h3')

After you have set a name for a different routing rule, you can invoke the routing rule in different places:

For example, in the template, you want to use this rule to generate url in the template:

Generate URL {% url 'h3' 2012} used in the template

Generate url in a function

Reverse ('h3pm, args= (2012,)) path: django.urls.reverse

You can also get this url in model:

Class NewType (models.Model):

Caption = models.CharField (max_length=16)

Def get_absolute_url (self):

"

Generate a URL for each object

Application: generate and view detailed URL in the object list, use this method!

: return:

"

# return'/% s bank% s'% (self._meta.db_table, self.id)

# or

From django.urls import reverse

Return reverse ('NewType.Detail', kwargs= {' nid': self.id})

Fourth, views view function.

Be careful! Before creating a view view function, the function must receive one parameter, request, which contains all the request information of the client browser! The parameter request is used to receive HttpRequest objects!

When a http request is made, two objects are generated:

Respectively, http request (HttpRequest object) and http response (HttpResponse object)

Introduce the common properties and methods of HttpRequest objects.

1.path: the full path of the request page, excluding the domain name.

2.method: HTTP request method, identified by a string (all uppercase) for example:

If req.method== "GET":

Do_something ()

If req.method== "POST":

Do_something_else ()

3.GET: a class dictionary object that contains all HTTP GET parameters

4.POST: a class dictionary object that contains all HTTP POST parameters

Supplement! It is also possible for the server to receive an empty POST request, that is, the form form submits the request through the HTTP POST method, but there may be no data in the form, so you cannot use if req.POST to determine whether the HTTP POST method is used; you should use if req.method== "POST".

Note a common method: request.POST.getlist ('')

5.COOKIES: a standard Python dictionary object that contains all cookies; keys and values are strings.

6.FILES: contains class dictionary objects for all uploaded files; each Key in FILES is the value of the name attribute in the tag, and each value in FILES is also a standard python dictionary object, including the following three Keys:

Filename: upload the file name.

Content_type: the Content Type of the uploaded file.

Content: the original content of the uploaded file.

6.user: is a django.contrib.auth.models.User object that represents the currently logged in user. If the visiting user is not currently logged in, user will be initialized to an instance of django.contrib.auth.models.AnonymousUser. You can use the is_authenticated () method of user to tell whether the user is logged in: if req.user.is_authenticated ()

(this property is available only when AuthenticationMiddleware in Django is activated)

7. Session: the only readable and writable attribute, which represents the dictionary object of the current session; this attribute is available only if you activate session support in Django.

Introduction to common methods and properties of HttpResponse objects:

For the HttpRequest object, it is created automatically by django, but the HttpResponse object must be created by ourselves. Each view request processing method must return a HttpResponse object.

# HttpResponse class is in django.http.HttpResponse.

Common methods of extending on HttpResponse objects:

# return HttpResponse ('') (only string objects can be returned! It is not recommended! )

Return render (request,'index.html') (recommended) (directly returns a html document, the first parameter is the httprequest object received by the view function, the second parameter is the file name of the html document, and it needs to be added that the file name will be found in the specified path, which is the name of the configuration file already written in the configuration file as settings.py)

2 in # render can also pass a third parameter, which is the template tag!

TEMPLATES = [

{

'BACKEND': 'django.template.backends.django.DjangoTemplates'

'DIRS': [os.path.join (BASE_DIR,' templates')]

Supplement! From django.shortcuts import HttpResponse,render is required before using render

Return redirect ("url to be redirected") # is used for address redirection!

Fifth, about the foundation of Template.

Template syntax:

1. Variable (use double curly braces to reference the variable).

Syntax format: `var_ name`

two。 Use。 The period is used to find the depth of the data in the variable.

In the examples so far, the simple parameter values we have passed through context are mainly strings, however, the templating system can handle more complex data structures very succinctly, such as list, dictionary, and custom objects.

The key to traversing complex data structures in Django templates is the period character (.).

Example 1: access the elements in the list in the template variable.

In python, if you want to access the data in the list, you need to use the index to access.

Indexing is also supported in django templates by using. (period).

> > from django.template import Template, Context

> t = Template ('Item two is `items`.`2`.) # item contains a list, followed by (.2) point 2 to take out the second element in the list (as in python, the index of the element starts from the 0th. )

> c = Context ({'items': [' value1', 'value2',' value3']})

> t.render (c)

'Item 2 is value3.'

Example 2: suppose you want to pass a Python dictionary to the template. To access the value of the dictionary through the dictionary key, you can also use the. Use the dot to get the value in the dictionary.

> > from django.template import Template, Context

> person = {'name':' bi**h jolin'', 'age':' 130'}

> t = Template ('`person`.`name `is `person`.`age `years old.')

> c = Context ({'person': person})

> t.render (c)

'bi**h jolin is 130 years old.'

Example 3: the period has another function in the template of django, which is to access the properties of an object.

For example, the datetime.date object of Python has year, month, and day attributes, which you can also access using periods in the template.

> > from django.template import Template, Context

> import datetime

> d = datetime.date (1993, 5,2)

> d.year

1993

> d.month

five

> d.day

two

> t = Template ('The month is `date`.`month `and the year is `date`.`year `.')

> c = Context ({'date': d})

> t.render (c)

'The month is 5 and the year is 1993.'

Example 4: in a custom class, a property of the object is accessed by adding a period after the object.

> > from django.template import Template, Context

> > class Person (object):

... Def _ _ init__ (self, first_name, last_name):

... Self.first_name, self.last_name = first_name, last_name

> t = Template ('Hello, `person`.`first _ name ``person`.`last _ name `.)

> c = Context ({'person': Person (' bitch', 'jolin')})

> t.render (c)

'Hello, bitch jolin.'

The dot can call the properties or methods of all objects within the python! This is very flexible!

> > from django.template import Template, Context

> t = Template ('`var `- `var`.`upper`-`var`.`isroom`')

> t.render (Context ({'var':' hello'}))

Hello-- HELLO-- False'

> t.render (Context ({'var':' 123'}))

'123123-True'

But!! Note that you do not * use parentheses when calling a method here and cannot pass parameters to the method; you can only call!!

3. Filter for variables in the template (filter):

Syntax format: {{obj | filter:param}}

3.1 add adds to the value of a variable.

{{value2 | add:3}}

At this point, value2=5.

3.2addslashes slashes the quotation marks in the variable.

3.3capfirst initials are capitalized.

3.4 cut removes the specified character from the string.

{{value3 | cut:''}}

# delimiter with null behavior

Value3='he llo wo r ld'

3.5 date formats the date string.

Import datetime

Value4=datetime.datetime.now ()

{{value4 | date:'Y-m-d'}}

3.6 default if the value is False, replace it with the default value set, otherwise it will use the original value.

{{value5 | empty'}} of default:'

# value5= []

Default_if_none: if the value is None, replace it with the default value set, otherwise the original value will be used.

3.8 operate on the a tag:

Value6=' Jump'

{{value6 | safe}}

# if there are other tags on the outside, such as the H2 tag, have the browser force the interpretation as the A tag.

3.8 string operation:

# value7='1234'

{{value7 | filesizeformat}}

{{value7 | first}}

# take the first character of the string

{{value7 | length}}

# take the length of the string

{{value7 | slice: ":-1"}}

# slicing

4. Use of template tag (using a combination of curly braces and percentages to indicate the use of tag)

Format: {% tags%}

4.1 if judgment tag: {% if%}

The {% if%} tag calculates a variable value, and if it is "true", that is, it exists, is not empty, and is not a Boolean value of false, the system displays everything between {% if%} and {% endif%}.

Example 1:

{% if num > = 100 and 8%}

{% if num > 200%}

Num is greater than 20000

{% else%}

Num greater than 100,200 less

{% endif%}

{% elif num < 100%}

Num less than 100

{% else%}

Num equals 100

{% endif%}

Attention!

The {% if%} tag accepts and,or or not to test multiple variable values or negate a given variable

{% if%} tag does not allow and and or to appear in the same tag at the same time, otherwise the logic is easy to be ambiguous!

4.2 for Loop judgment tag: {% for%}

The {% for%} tag allows you to traverse the elements of a sequence sequentially, and the template system renders everything between {% for%} and {% endfor%} each time.

{% for obj in list%}

`obj`.`name `

{% endfor%}

Reverse cycle:

The django template also supports adding reversed to the tag to reverse the order of the list:

The syntax format is as follows.

{% for obj in list reversed%}

...

{% endfor%}

For loop tags can also be nested:

{% for country in countries%}

`roomy`.`name `

{% for city in country.city_list%}

`city'

{% endfor%}

{% endfor%}

Attention! The for loop in the django template does not support continue and breakthroughs!

The {% for%} tag has a built-in forloop template variable that contains attributes that can give you some information about the loop.

Forloop.counter represents the number of loops, counting from 1, and the first loop is set to 1

{% for item in todo_list%}

`forloop`.`counter `: `item`

{% endfor%}

The forloop.counter0 function is the same as forloop.counter, but it counts from 0, and the first loop is set to 0.

Count forloop.revcounter in reverse order up to 1

Forloop.revcounter0 count in reverse order, up to 0

The value of forloop.first is True when it first loops.

Application scenarios:

{% for object in objects%}

{% if forloop.first%} {% else%} {% endif%}

`object'

{% endfor%}

Be careful! The forloop variable can only be obtained in a loop, and forloop becomes useless when the template parser reaches {% endfor%}.

When no value is available for this loop, perform the actions under the {% empty%} tag:

`li'

{% for i in li%}

`forloop`.`counter0`-`i`

{% empty%}

This is empty!

{% endfor%}

4.3 {% csrf_token%}: csrf_token tag (a security mechanism).

The tag used to generate csrf_token to prevent cross-site verification. Note that if you use the render_to_response method in view's index, it won't work.

The principle is that an input tag is generated and submitted to the background along with other form tags.

4.4 {% with%}: replace complex variable names with simpler variable names.

{% with total=fhjsaldfhjsdfhlasdfhljsdal%} `total `{% endwith%}

This variable name only takes effect in the with tag!

4.5 {% verbatim%}: render is disabled and variables in the template will not be parsed.

{% verbatim%}

`hello'

{% endverbatim%}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report