Writing_first_django_app_part3
In Django, Web pages and other content are presented through views, and each view is represented by a simple Python function, and Django chooses a view by checking the URL
Simple general form of URL Pattern:url, eg:/newsarchive/<year>/<month>/
Python uses ' Urlconfs ' to match URL patterns to views
Let's look at a simple view example
# polls/view.pyfrom django.http Import httpresponsedef Index (Request): return HttpResponse ("Hello, World.") You ' re at the polls index. ")
We need to map it to a URL to access it, here we need a urlconf to create a urlconf in the polls directory, first create a file urls.py, add the code:
From django.conf.urls import patterns, urlfrom polls import viewsurlpatterns = Patterns (", url (r ' ^$ ', Views.index, n ame = ' index '),
The next step is to insert the new urlconf in the root urlconf
# mysite/urls.pyfrom Django.conf.urls Import patterns, include, urlfrom django.contrib import adminurlpatterns = Patterns ("', # Examples: # URL (r ' ^$ ', ' mysite.views.home ', name= ' home '), # URL (r ' ^blog/', include (' Blog.urls ')), URL (r ' ^polls/', include (' Polls.urls ')), URL (r ' ^admin/', include (Admin.site.urls)),)
After the modification, the server will be restarted, and the interface of Hello World can be seen by accessing localhost:8000/polls/. The process of adding a view just now is to add a new view in poll/views.py, then create a new urlconf in polls/urls.py and finally include it in the mysite/urls.py of the root.
Now add a few more views
# polls/views.pyfrom django.shortcuts import renderfrom django.http import HttpResponse# Create your Views Here.def index (Request): Return HttpResponse ("Hello, World.") You ' re at the polls index. ") def detial (Request, question_id): Response = "You ' re looking at the results of question%s '" Return HttpResponse (res Ponse% question_id) def vote (Request, question_id): Return HttpResponse ("You ' re voting on question%s."% question_id) /pre>
# polls/urls.pyfrom Django.conf.urls Import patterns, urlfrom polls import viewsurlpatterns = Patterns (", #/polls/< C1/>url (R ' ^$ ', views.index, name = ' index '), # eg:/polls/5/ url (r ' ^ (? p<question_id>\d+)/$ ', views.detail, name = ' Detail '), # eg:/polls/5/results/ url (r ' ^ (? p<question_id>\d+)/results/$ ', views.results, name = ' result '), # eg:/polls/5/vote/ url (r ' ^ (? p<question_id>\d+)/vote/$ ', views.vote, name = ' vote '), )
Because the polls urlconf is already added to the urls.py in the root directory, you do not have to add it again (? p<question_id>\d+) to extract the contents of the matching \d+, and then assign the value to the keyword question_id as a parameter passed into the class to handle
Each view will have one of two functions, returning a HttpResponse or Http404.
Now we're trying to add a real feature to the view, showing the latest 5 poll questions in the index interface, sorted by time:
# polls/views.pyfrom django.http Import httpresponsefrom polls.models import questiondef Index (Request): Latest_ Question_list = Question.objects.order_by ('-pub_date ') [: 5] output = ', '. Join ([P.question_text for P in Latest_ Question_list]) return HttpResponse (Output) # Leave the rest of the views (detail, results, vote) unchanged
We want to use our own template to display the question list, create a directory templates in the polls directory, create a directory polls inside, and build the file index.html inside:
# mysite/polls/templates/polls/index.html{% if latest_question_list%} <ul> {% for question in Latest_ Question_list%} <li><a href= "/polls/{{question.id}}/" >{{question.question_text}}</a></ li> {% endfor%} </ul>{% Else%} <p>no polls is available.</p>{% endif%}
Here each question as a link to show,
Then modify the view's code to use this template:
# polls/views.pyfrom django.http Import httpresponsefrom django.template import RequestContext, Loaderfrom polls.models Import Questiondef Index (Request): latest_question_list = Question.objects.order_by ('-pub_date ') [: 5] Template = Loader.get_template (' polls/index.html ') context = RequestContext (request, { ' Latest_question_ List ': Latest_question_list, }) return HttpResponse (Template.render (context))
It uses Template.loader to invoke the template, then creates a RequestContext object to make the request, returns the HttpResponse object after the template has been rendered
Render () function
The first parameter is the request object, the second argument is the template name, and the third argument can select a dictionary to pass some keyword arguments. Returns a HttpResponse object after rendering the requested content
Raising a 404 error
# polls/views.pyfrom django.http Import http404from django.shortcuts import renderfrom polls.models import Question# ... d EF detail (Request, question_id): try: question = Question.objects.get (pk=question_id) except Question.doesnotexist: Raise Http404 ("Question does not exist") return render (Request, ' polls/detail.html ', { ' Question ': question})
Temporary detail.html:
# polls/templates/polls/detail.html{{Question}}
The above code returns a 404 error when the question object is not found, and can be processed at once using the get_object_or_404 () function.
From django.shortcuts import get_object_or_404, renderfrom polls.models import question# ... def detail (request, Question _ID): question = get_object_or_404 (question, pk=question_id) return render (Request, ' polls/detail.html ', {' Question ': question})
This allows the test to be successful directly when the object is obtained, or it returns an error
Use the Templates system
# polls/templates/polls/detail.html
The template system can pass the '. ' To access the properties of a variable, such as Question.question_text
namespacing URL NamesThere is currently only one application when the name of the URL does not conflict, but if the number of applications is increased to multiple, there may be an application with the same URL name, which can be resolved by adding scopes:
# mysite/urls.pyfrom Django.conf.urls Import patterns, include, urlfrom django.contrib import adminurlpatterns = Patterns (', url (r ' ^polls/', include (' Polls.urls ', namespace= "polls")), URL (r ' ^admin/', include (Admin.site.urls)) ,)
Now change polls/templates/polls/index.html to:
<li><a href= "{% url ' polls:detail ' question.id%}" >{{Question.question_text}}</a></li>
Django Tutorial Part3