Boston Python Workshop/Saturday/Web app project: Difference between revisions

Revert to pre-spam
imported>Paulproteus
(Revert to pre-spam)
 
(16 intermediate revisions by 9 users not shown)
Line 604:
=== Raising 404 ===
 
Now, let's tackle the poll detail view -- the page that displays the question for a given poll. Continue editing the ''views.py'' file. This view uses Python ''exceptions'':
 
from django.http import Http404
Line 617:
The new concept here: The view raises the Http404 exception if a poll with the requested ID doesn't exist.
 
If you'd like to quickly get the above example working, just create a new template file and name it ''detail.html''. Enter in it just one line of code:
 
<pre>
Line 623:
</pre>
 
willto get you started for now.
 
Add it to a new template file that you create, ''detail.html''.
 
Does your detail view work? Try it: http://127.0.0.1:8000/polls/1/
 
You can also try to load a poll page that does not exist, just to test out the pretty 404 error: http://127.0.0.1:8000/polls/32/
 
=== Adding more detail ===
Line 647:
 
Method-calling happens in the {% for %} loop: poll.choice_set.all is interpreted as the Python code poll.choice_set.all(), which returns a sequence of Choice objects and is suitable for use in the {% for %} tag.
 
Load the new detail page in your browser: http://127.0.0.1:8000/polls/1/ The poll choices now appear.
 
=== Adding some style ===
Line 681 ⟶ 683:
* Since we're creating a POST form (which can have the effect of modifying data), we need to worry about Cross Site Request Forgeries. Thankfully, you don't have to worry too hard, because Django comes with a very easy-to-use system for protecting against it. In short, all POST forms that are targeted at internal URLs should use the {% csrf_token %} template tag.
 
The {% csrf_token %} tag requires information from the request object, which is not normally accessible from within the template context. To fix this, a small adjustment needs to be made to the detail view in the "views.py" file, so that it looks like the following:
 
<pre>
Line 692 ⟶ 694:
</pre>
 
The details of how this works are explained in the [http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext documentation for RequestContext].
 
Now, let's create a Django view that handles the submitted data and does something with it. Remember, in Tutorial 3, we created a URLconf for the polls application that includes this line:
Anonymous user