Showing posts with label Django creates the first project. Show all posts
Showing posts with label Django creates the first project. Show all posts

Django Templates Details Tutorial





Django template


In the previous chapter we use django.http.HttpResponse () to output "Hello World!". This way the data and view mixed together, do not meet the Django MVC thinking.

In this section we will detail the application of the Django template, which is a text that separates the presentation and content of the document.

Template application example

We will follow the previous section of the project will be in the HelloWorld directory to create templates directory and create hello.html file, the entire directory structure is as follows:

HelloWorld/
|-- HelloWorld
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- settings.py
|   |-- settings.pyc
|   |-- urls.py
|   |-- urls.pyc
|   |-- view.py
|   |-- view.pyc
|   |-- wsgi.py
|   `-- wsgi.pyc
|-- manage.py
`-- templates
    `-- hello.html
hello.html  The file code is as follows:

HelloWorld/templates/hello.html  File code:

<H1> {{hello}} </ h1>

From the template we know that variables use double parentheses.

Next we need to explain the path to the template file to Django, modify HelloWorld / settings.py, modify DIRS in TEMPLATES to [BASE_DIR + "/ templates", as follows:

HelloWorld/HelloWorld/settings.py File code:

...TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR+"/templates",], # Modify the location 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ...

We now modify view.py, add a new object for submitting data to the template:

HelloWorld/HelloWorld/view.py File code:
# -*- coding: utf-8 -*- #from django.http import HttpResponse from django.shortcuts import render def hello(request): context = {} context['hello'] = 'Hello World!' return render(request, 'hello.html', context)

You can see that here we use render to replace the previously used HttpResponse. Render also uses a dictionary context as a parameter.

The key "hello" of the element in the context dictionary corresponds to the variable "{{hello}}" in the template.

And then visit visit http://127.0.0.1:8000/hello, you can see the page:




So we completed the use of templates to output data, in order to achieve data and view separation.

Next we will introduce the syntax rules commonly used in templates.

Django template tags

If / else tag

The basic syntax is as follows:
{% if condition %}
     ... display
{% endif %}
Else
{% if condition1 %}
   ... display 1
{% elif condiiton2 %}
   ... display 2
{% else %}
   ... display 3
{% endif %}

According to the conditions to determine whether the output. If / else support nesting.

The {% if%} tag accepts the, or or not keywords to determine multiple variables, or negate the variables, for example:


{% if athlete_list and coach_list %}
     Both the athletes and coaches variables are available.
{% endif %}
For the label

{% For%} allows us to iterate over a sequence.

Similar to the case of Python's for statement, the loop syntax is for X in Y, Y is the sequence to be iterated and X is the name of the variable used in each particular loop.
In each iteration, the template system renders all content between {% for%} and {% endfor%}.
For example, given an athlete list for the athlete_list variable, we can use the following code to display the list:
<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% endfor %}
</ul>
Add a reverse to the label so that the list is reversed by iteration:
{% for athlete in athlete_list reversed %}
...
{% endfor %}
Can be nested using {% for%} tags:
{% for athlete in athlete_list %}
    <h1>{{ athlete.name }}</h1>
    <ul>
    {% for sport in athlete.sports_played %}
        <li>{{ sport }}</li>
    {% endfor %}
    </ul>
{% endfor %}
Ifequal / ifnotequal tag
The {% ifequal%} tag compares the two values and displays all the values in {% ifequal%} and {% endifequal%} when they are equal.
The following example compares two template variables user and currentuser:



{% ifequal user currentuser %}
    <h1>Welcome!</h1>
{% endifequal %}
Similar to {% if%}, {% ifequal%} Supports optional {% else%} tags: 8


{% ifequal section 'sitenews' %}
    <h1>Site News</h1>
{% else %}
    <h1>No News Here</h1>
{% endifequal %}

Annotation label Django comment using {# #}.

{# This is a comment #}

filter
The template filter can be modified before the variable is displayed, and the filter uses the pipe character as follows:
{{ name|lower }}

{{Name}} After the variable is processed by the filter, the document uppercase conversion text is lowercase. The filter pipe can be * jack *, both said that the output of a filter pipe can be used as the input of the next pipe:
{{ my_list|first|upper }}

The above example converts the first element and converts it to uppercase. Some filters have parameters. The parameters of the filter follow the colon and are always enclosed in double quotation marks. E.g:
{{ bio|truncatewords:"30" }}
This will display the first 30 words of the variable bio. Other filters: Addslashes: Adds a backslash to any backslash, single or double quotation marks. Date: format the date or datetime object in the specified format string parameter, instance:
{{ pub_date|date:"F j, Y" }}
Length: Returns the length of the variable. Include tags The {% include%} tag allows you to include the contents of other templates in the template. The following example contains the nav.html template:
{% include "nav.html" %}
Template inheritance Templates can be reused in an inherited manner. Next we add the base.html file in the templates directory of the previous project, as follows:

HelloWorld/templates/base.html File Code:


!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Django Girls Blog</title> </head> <body> <h1>Django Girls Blog</h1> <p>[<Post:My second Post>],[<Post:My first Post>]</p> {% block mainbody %} <p>original</p> {% endblock %} </body> </html>

In the above code, the block tag named mainbody is the part that can be replaced by the successor.
All {% block%} tags tell the template engine that the subpages can override these sections.
Hello.html inherited base.html, and replace the specific block, hello.html modified code as follows:


The first line of code shows that hello.html inherits the base.html file. You can see that the same name of the block tag here to replace the corresponding base.html block.

Re-visit the address http://127.0.0.1:8000/hello, the output is as follows:





Django creates the first project

Django creates the first project

In this chapter we will introduce the Django management tools and how to use Django to create the project, the first project we use HelloWorld to order the project.

Test Release Notes:

Python 2.7.10
Django 1.10.6

Django management tools

After installing Django, you should now have the available administrative tools django-admin.py. We can use django-admin.py to create a project:
We can look at the following django-admin.py command description:

[root@solar ~]# django-admin.py
Usage: django-admin.py subcommand [options] [args]

Options:
  -v VERBOSITY, --verbosity=VERBOSITY
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings=SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, the
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath=PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Raise on exception
  --version             show program's version number and exit
  -h, --help            show this help message and exit

Type 'django-admin.py help <subcommand>' for help on a specific subcommand.

Available subcommands:

[django]
    check
    cleanup
    compilemessages
    createcachetable
……abbreviated part……

 Create the first project
Use django-admin.py to create a HelloWorld project

django-admin.py startproject HelloWorld

After the creation is complete, we can view the directory structure of the next project:
Catalog Description:

HelloWorld: container of the project.

Manage.py: A useful command-line tool that allows you to interact with the Django project in a variety of ways.

HelloWorld / __ init__.py: An empty file that tells Python that the directory is a Python package.
HelloWorld / settings.py: The settings / configuration of the Django project.
HelloWorld / urls.py: the Django project URL declaration; a Django-driven site "directory".
HelloWorld / wsgi.py: A WSGI-compliant Web server portal to run your project.

Next we enter the HelloWorld directory and enter the following command to start the server:

python manage.py runserver 0.0.0.0:8000

0.0.0.0 to other computers can be connected to the development server, 8000 for the port number. If not, then the port number defaults to 8000.

In the browser input your server ip and port number, if the normal start, the output is as follows:




View and URL configuration

Create a new view.py file in the HelloWorld directory under the previously created HelloWorld directory and enter the code:

HelloWorld / HelloWorld / view.py file code:

from django.http import HttpResponse def hello(request): return HttpResponse("Hello world ! ")


Next, bind the URL with the view function. Open the urls.py file, delete the original code, copy and paste the following code into the urls.py file:

HelloWorld / HelloWorld / urls.py File Code:

from django.conf.urls import url from . import view urlpatterns = [ url(r'^$', view.hello), ]
The entire directory structure is as follows:

$ tree
.
|-- HelloWorld
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- settings.py
|   |-- settings.pyc
|   |-- urls.py              # url deploy
|   |-- urls.pyc
|   |-- view.py              # Added view file
|   |-- view.pyc             # Compiled view file
|   |-- wsgi.py
|   `-- wsgi.pyc
`-- manage.py
When finished, start the Django development server and access the browser in the browser and access:




We can also modify the following rules:

HelloWorld/HelloWorld/urls.py File code:


from django.conf.urls import url

from . import view

urlpatterns = [ url(r'^hello$', view.hello),

 ]

Through the browser to open http://127.0.0.1:8000/hello, the output is as follows



Note: If the code changes in the project, the server will automatically monitor the code changes and automatically reload, so if you have started the server without a manual restart.
 
Url () function

Django url () can receive four parameters, are two mandatory parameters: regex, view and two optional parameters: kwargs, name, then the details of these four parameters.

Regex: regular expression, matching the URL will perform the corresponding second parameter view.

View: Used to execute a URL request that matches a regular expression.
Kwargs: parameters of the dictionary type used by the view.
Name: used to reverse the URL.

Popular Posts