MasterofProject

Public opinion survey Django implementation (three)

Label DjangoTemplatesURL
356 people read comments(5) Collection Report
Classification:

We begin our journey in the second section. We will continue to Web-poll applications, and will focus on creating a common interface - "Views".

philosophy

A view is a Web page in your Django application, which generally serves a particular function and a particular template. For example, in a blog application, you may have the following views:

  • Blog home - shows the latest entry
  • Entry detail page - a fixed link page for a single purpose
  • File pages based on year - showing entries for all months of a given year
  • Month based filing page - all entries for a given month
  • Show the archive page to all the entries on the day
  • Comment action - handle the issue of a comment on a given item.

In our poll application, we will have the following 4 views:

  • Problem index page - to show some of the recent problems
  • Details page - showing a problem text, no result is just a ballot form.
  • Problem result page - shows the results of a particular problem
  • Vote - to deal with specific issues of voting action

In web, Django pages and other contents are transmitted via view. Each view is represented by a simple Python function (or method). Django will be selected by the URL to select the view (in detail, which is the address part of the domain name).

You might encounter an address such as "ME2/Sites/dirmod.asp sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B". You will be happy to learn that Django allows us to be more URL mode.

A URL model is a simple model of a URL - for example:/newsarchive/<year>/<month>/.

In order to be able to get from a web site to a view, Django uses the 'URLconfs' we have learned. A URLconfs mapping URL model (described as a regular expression) to the view.

This section provides a basic introduction to the use of URLconfs.

Write your first view

Let's write the first view. Open the file polls/views.py and add the following Python code:

FromDjango.httpImportHttpResponse

Def Index(request):
    ReturnHttpResponse ("World.You, are at the polls index. Hello")

This may be the simplest view in Django. In order to call this view, we need to map it to a URL - and we need a URLconf.

In order to create a URLconf in the polls directory, create a file by urls.py. Your app directory should look like this:

Polls directory:

Just admin.py
Just admin.pyc
Just __init__.py
Just __init__.pyc
Just migrations
We had 0001_initial.py
We had 0001_initial.pyc
We had __init__.py
, __init__.pyc
Just models.py
Just models.pyc
Just tests.py
Just urls.py
- views.py

Include the following code in polls/urls.py:

FromDjango.conf.urlsImportPatterns, URL

FromPollsImportViews

Urlpatterns = patterns (=.',
(URLR'^$', views.index, name='index'),
)

The next step is to point out the root URLconf in the polls.urls module. Insert a include (in mysite/urls.py), as is the following:

FromDjango.conf.urlsImportPatterns, include, URL
FromDjango.contribImportAdmin

Urlpatterns = patterns (=.',
    # Examples:
    # URL (r'^$','mysite.views.home', name='home'),
    # URL (r'^blog/', include ('blog.urls')),
(URLR'^polls/'Include ('polls.urls')),
(URLR'^admin/', include (admin.site.urls)),
)

Now we've connected the index view to the URLconf. Open a link in a browserHttp://localhost:8000/polls. And you will see the text "Hello, are at the polls index. world.You", which is defined in your index view.

URL () function is passed four parameters, two must be: regular and view, there are two optional: kwargs and name. At this time, it is worthwhile to review these parameters.

URL () parameters: regex

The term "regex" is a common abbreviation that represents a "regular expression", which is used for string matching syntax, or in the case of the URL model. Django at the beginning of the first regular expression, compare all the URL addresses to see if they match, until the match is found.

Note that these regular expressions do not search for GET and POST parameters, or the domain name. For example, in a requestHttp://www.example.com/myappIn, URLconf will go to see the myapp/. On requestHttp://www.example.com/myapp/? Page=3?In, URLconf will find myapp/.

Here we do not need to be very professional regular expression of learning, just to understand the basic model on the line.

Finally, a performance Alert: these regular expressions are compiled when the URLconf module is loaded for the first time. They run very fast.

URL () parameters: View

When Django finds a regular match, Django calls a particular view function, which has the most HttpRequest object and the other values that are captured from the regular expression. If the regex uses a simple capture, the value is passed as a location parameter. If it is private name capture value will be as a key value parameter. We will give examples of subroutine.

URL () parameters: kwargs

Free keyword arguments can be passed from one directory to the destination view. We will not use this feature here.

URL () parameters: name

Naming your URL in a specific template in the Django allows you to find him anywhere. This is a very powerful feature that allows you to create a single document to make a global change to your project's URL model.

Write more views

Now let's add a more view to the polls/views.py. These views are slightly different, because they use a parameter:

Def Detail(request, question_id):
    ReturnHttpResponse ("Are looking at question%s. You"% question_id)

Def Results(request, question_id):
Response ="Are looking at the results of question You%s."
    ReturnHttpResponse (response% question_id)

Def Vote(request, question_id):
    ReturnHttpResponse ("Are voting on question%s. You"% question_id)

For these new views, we need to add an index to the polls/urls.py:

FromDjango.conf.urlsImportPatterns, URL

FromPollsImportViews

Urlpatterns = patterns (=.',
    # ex: /polls/
(URLR'^$', views.index, name='index'),
    # ex: /polls/5/
(URL(r'^? P<question_id>\d+) /$', views.detail, name='detail'),
    # ex: /polls/5/results
(URLR'^ (P<question_id>\d+) /results/$', views.results, name='results'),
    # ex: /polls/5/vote/
(URLR'^ (P<question_id>\d+) /vote/$', views.vote, name='vote'),
)

We open our browser to see, enter the url:Https://localhost:8000/polls/34/. She will run the detail () function and display the corresponding content, as well as we can test the other functions:

We have a look:

View specific issues
Write the picture here.

View the results of the specified problem
Write the picture here.

Vote to a specific question
Write the picture here.

Here we look at the specified process url:

Write the picture here.

When someone requests a page from your web site, that is, when the request, "polls/34/", Django will load the mysite.urls module, because he points to the ROOT_URLCONF settings. He finds the variable name urlpatterns, and the regular expression is converted to the order. We use the include () function to point to other URLconfs. Note that for regular expressions (include) the function without $(end-of-string match charactor. At the end of the string matching characters), but with a slash. When Django meets include (), he will be transmitted to the corresponding string containing the URLconfs in order to further processing.

The idea behind include () is to make it easier to insert and run URL. Since polls in their own URLconfs (polls/urls.py), they can be placed in the "/polls/" or placed in the "/fun_polls" or "/content/polls", or any other root path, app can still work.

Here's what happens when the user enters the /polls/34:

  • Django will find a matching '^polls/'
  • Then, Django will intercept a part of the match string ("polls/"), and the remaining text - "34/" - sent to the 'polls.urls' for further processing, processing is completed, resulting in the call detail () view:
    Detail (object> request=<HttpRequest, question_id='34')

Write views that can really do things

Each view is responsible for doing one of two things: return a HttpResponse object that contains the request page, or send an exception such as Http404. The rest is up to you.

Your view can be read from the database. He can use a template system such as the Django - third party template system -. He can generate a PDF file, output XML, create an ZIP file, or whatever you want, all of which are done using the Python library.

All Django requirements are HttpResponse or an exception.

Because he is convenient, so let us use the Django's own database API, we talked about in the first section. The following is a small portion of the index () view, which is used to display the most recent 5 voting problems in the system, separated by a comma, according to the public date.

Location: polls/views.py

FromDjango.httpImportHttpResponse

FromPolls.modelsImportQuestion


Def Index(request):
Latest_question_list = Question.objects.order_by ('-pub_date'[):Five]
Output =','.join ([p.question_textForPInLatest_question_list])
    ReturnHttpResponse (output)

# other function did not change

Here's a question: in the view of the page design is hard to encoding. If you want to change the appearance of the page, you have to edit the Python code. So, let's use the Django template system to separate the design from the Python code by creating a view template that you can use.

First, create a directory called templates in your polls directory, and Django will search the template here.

TEMPLATE_LOADERS Django set contains a series of know how to introduce a template from a variety of source calls. The default is a django.template.loaders.app_directories.Loader, it will search in every INSTALL_APPS in the "templates" sub directory - this is how to find polls Django template, even if we do not modify the TEMPLATE_DIRS settings.

In the templates directory we just created, create another directory called polls, and create a file called index.html in polls. That your template should be polls/templates/polls/index.html. Since we've learned how the app_directories template is loaded, we can point to the template by polls/index.html in Django.

We add the following code to the index.html.

{%IfLatest_question_list%}
    <UL>
    {%ForQuestionInLatest_question_list%}
        <Li>
            <A Href="/polls/Turning question.id}}/">Turning question.question_text}}< /A>
        < /Li>
    {%Endfor%}
    < /UL>
{%Else%}
    <P>Polls are available. No< /P>
{%Endif%}

Let's update the index view in polls/views.py:

FromDjango.httpImportHttpResponse
FromDjango.templateImportRequestContext, loader

FromPolls.modelsImportQuestion


Def Index(request):
Latest_question_list = Question.objects.order_by ('-pub_date'[):Five]
Template = loader.get_template ('polls/index.html')
Context = RequestContext (request, {
        'latest_question_list'Latest_question_list,
})
    ReturnHttpResponse (template.render (context))

The code to load the template called polls/index.html, and he passed to the context. Context is a dictionary that maps a variable name of the template to a Python object.

Input in the browser:Http://localhost:8000/polls/To load the page, before I manually added a problem, so my display is like this:

Write the picture here.

Abbreviations: render ()

Loading the template, filling a context and returning a HttpResponse object with the result is a common way. Django provides a shortcut, the following is a shortcut to index () view of the way to achieve:

FromDjango.httpImportHttpResponse
FromDjango.shortcutsImportRender

FromPolls.modelsImportQuestion


Def Index(request):
Latest_question_list = Question.objects.order_by ('-pub_date'[):Five]
Context = {'latest_question_list'Latest_question_list}
    ReturnRender (request,"Polls/index.html"Context)

Note that once we use this method, we do not need to introduce RequestContext, loader.

Render () function uses the request object as his first parameter, the name of the template as the second parameter, and the dictionary as an optional parameter. He returns a HttpResponse object that is rendered to a given template with a given context.

Point out 404 errors

Now, we have to solve the problem of view - the given poll display question text page. Here is the view:

FromDjango.httpImportHttp404
FromDjango.shortcutsImportRender

FromPolls.modelsImportQuestion
#...
Def Detail(request, question_id):
    Try:
Question = Question.objects.get (pk=question_id)
    ExceptQuestion.DoesNotExist:
        RaiseHttp404 ("Does not exist Question")
    ReturnRender (request,'polls/detail.html'{.'question'Question})

The new concept is this: if a problem with a request for ID does not exist, the view will present a Http404 exception.

We will detail the back in the polls/detail.html should put what, here we use a faster way to make him work.

Polls/templates/polls/detail.html

TurningQuestion}}

Shortcut: get_object_or_404 ()

Django provides us with a shortcut, and we'll have to rewrite it:

FromDjango.shortcutsImportGet_object_or_404, render

FromPolls.modelsImportQuestion
#...
Def Detail(request, question_id):
Question = get_object_or_404 (Question, pk=question_id)
    ReturnRender (request,'polls/detail.html'{.'question'Question})

Let's look at the running results:

Write the picture here.

Using template system

Now we're back to the detail () view. Given the context variable question, the following is what our polls/detail.html template looks like:

<H1>Turning question.question_text}}< /H1>

<UL>
{%ForChoiceInQuestion.choice_set.all%}
    <Li>Turning choice.choice_text}}< /Li>
{%Endfor%}
< /UL>

Let's look at the running results:

Write the picture here.

Template system uses point query syntax to access variable attributes. In the example of turning question.question_text}}, first of all, Django do a search in the dictionary object in question. If it fails, it will try to search for a property. If the property searches the night market, he will try a list index search.

Function call occurs in {% for} cycle: Question.choice_set.all Question.choice_set.all is the native Python code, he returned to the iterative choice object, and in {% for} use is appropriate.

Remove URL hard encoding in the template

Remember, when we write the question link in the polls/index.html template, the link is also hard to encoding:

<Li><A Href="/polls/TurningQuestion.id}}/">TurningQuestion.question.text}}< /A>< /Li>

When there are a lot of templates in a project, we will face a challenge if we change the URL. However, since you in () function polls.urls the URL of the defines the parameter name, you can use the {% URL} template tags to remove in your URL configuration specific URL path dependence.

<Li><A Href="URL'detail'{% question.id%}">TurningQuestion.question_Text}}< /A>< /Li>

The way in which this work is to search for the definition of URL in polls.urls. You can see exactly where the name of 'URL' is defined by the 'detail'.

...
The'name'value as called by # the {% URL%} template tag
URL (R'^ (? P<question_id>\d+) /$', views.detail, name='detail'),
...

If you want to change the poll view of the detail URL, or polls/specifics/12/ instead of the original template, you might want to change him in polls/urls.py.

...
Added the word'specifics'#
URL (R('^specifics/? P<question_id>\d+) /$', views.detail, name='detail'),
...

URL namespace

In our project, there is only one app, polls. In actual Django project, there may be 5, 10, 20 or more app. So how does Django distinguish between URL names? For example, APP polls has a detail view, and another app on the same project also has a detail view. So how does Django know which app view it?

The answer is to add a namespace to your root URLconf. In the mysite/urls.py file, modify it to include a namespace.

FromDjango.conf.urlsImportPatterns, include, URL
FromDjango.contribImportAdmin

Urlpatterns = patterns (=.',
(URLR'^polls/'Include ('polls.urls', namespace="Polls")),
(URLR'^admin/', include (admin.site.urls)),
)

Now modify your polls/index.html template:

That's the way it is:

<Li><A Href="URL'detail'{% question.id%}">TurningQuestion.question_Text}}< /A>< /Li>

Now add namespace:

Polls/templates/polls/index.html
<Li><A Href="URL'polls:detail'{% question.id%}">TurningQuestion.question_Text}}< /A>< /Li>
top
One
tread
Zero
Guess you're looking for
View comments
* the above user comments only represent their personal views, does not represent the views or position of the CSDN website
    personal data
    • Visit51989 times
    • Integral:Two thousand five hundred and eleven
    • Grade
    • Rank:8420th name
    • Original177
    • Reproduced:3
    • Translation:8
    • Comments:36
    Blog column
    Latest comments