Beginning Django E Commerce
398 pág.

Beginning Django E Commerce

DisciplinaProgramação I24.501 materiais279.087 seguidores
Pré-visualização50 páginas
called contexts. 
A Context object takes one optional parameter, which is a Python dictionary of name-value pairs. 
These values are the variables you can use in your templates, and reference by name, when you return 
them to the response. 
So, if we refactored what we did previously to follow Django standards, we might create a file called 
sample.html within our project\u2019s template directory (which we haven\u2019t made yet) containing the 
following HTML: 
<html><body>Welcome to {{ site_name }}.</body></html> 
and we would change our Python view function to look like this: 
def catalog(request): 
 my_context = Context({ 'site_name': 'Modern Musician' }) 
 response_html = return_to_string('sample.html', my_context) 
 return HttpResponse(response_html) 
This makes things much simpler and more flexible. You create a Context object and pass it a 
Python dictionary with one entry: the name of your site. You then call the return_to_string() 
function, passing it the name of your template and the Context object you created. Then, like before, 
you return the response. 
Don\u2019t worry if you\u2019re completely lost about how things are supposed to really come together in 
Django at this point. You might be wondering how Django knows where to look when it\u2019s loading your 
template file, or why we\u2019d do anything as inane as specifying our site\u2019s name in a local variable in a 
single view function. I\u2019ve only provided these examples so that you get some idea of how you create a 
template and the means by which you pass in any variables. 
In particular, take note of the double curly-braces in the template: {{ site_name }}. That is 
Django\u2019s syntax for a variable. When the Django templating engine parses this code, it will stick the 
name of your site\u2014in this case, \u201cModern Musician\u2014in the {{ site_name }} placeholder. 
Advanced Templates with Inheritance 
As a Django programmer, you\u2019ll be loading templates and creating Context objects very often during the 
development of your site. For this reason, you want to take the easiest approach possible. We\u2019re now 
going to leave the realm of theoretical examples and implement a real page with the tactics that will 
carry us through the rest of the book. 
Templates are made easier in Django with functionality referred to as template inheritance. If you\u2019re 
familiar with object-oriented programming, template inheritance is much like class inheritance: child 
templates take the content of their parent template, and custom content can be added to the child to 
override and extend that of the parent. 
Let\u2019s put this thought into action. First, create a new folder in the root of your project and called it 
templates. Then open up your file and find the variable TEMPLATE_DIRS, which should be 
an empty tuple by default. You\u2019ll need to put the absolute path on your system to the directory or 
directories where you plan to keep your template files. On the Ubuntu box I\u2019m using, this looks like this: 
On a Windows machine, your path will likely start with C:/, and should take only forward slashes. 
Make sure not to copy the backslashes from your Explorer window because they won\u2019t work. 
A quick word about what we just did: we opted to put the template files into a directory inside our 
project. Depending on your particular requirements, this may not be what you want. The Django 
community, as well as the Python community at large, prides itself on maximum flexibility, and being 
able to reuse work that you\u2019ve already done in other Django projects is a large component of that 
flexibility. It\u2019s not a requirement that your template directory is within your project... it could be just 
about anywhere on your system that your user account has the proper permissions to access. 
I\u2019ve chosen to contain them within our project for simplicity and convenience, and because I\u2019m 
pretty sure any future sites I\u2019ll be coding will have drastically different layout needs, I want to set things 
up so that later, when I need to edit one site, I don\u2019t have to edit them all. I prefer the templating for each 
project be decoupled from all of the others, and any base similarities can merely be copied from the 
other projects at the start of development. Despite this philosophy, if you think you\u2019ll be doing lots of 
other projects and want to put them elsewhere, outside of your directory, I would be the first person to 
insist on it. 
Typically, to allow yourself some \u201cwiggle room\u201d as far as the templates go, Django templates should be 
three levels deep. The template in the first level contains all of the elements that are common to all HTML 
pages on your site, like the opening and closing html, head, and body tags, and any meta, link, or script 
tags inside of the head tags. The template directly below this will contain the HTML for your site\u2019s overall 
layout structure, marked up with id and class attributes for CSS styling. The third and last level should 
contain content specific to individual pages. To start creating our templates, let\u2019s look at the needs that will 
be fundamental to most every HTML page on your site. You can safely assume you\u2019ll have a Document 
Type Declaration, and opening and closing html, head, body, title, and meta tags. Create a file in the 
templates directory you just created and call it base.html. Put the following code into the file: 
<!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot; &quot;XHTML1-s.dtd&quot; ><html 
xmlns=&quot;; xml:lang=&quot;en&quot; lang=&quot;en&quot;>
 <meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /> 
 <title>{% block title %}{% if page_title %}{{ page_title }} - {% endif %} \ufffd 
 {{ site_name }}{% endblock %}</title> 
 <meta name=&quot;keywords&quot; content=&quot;{{ meta_keywords }}&quot; /> 
 <meta name=&quot;description&quot; content=&quot;{{ meta_description }}&quot; /> 
 {% block site_wrapper %}{% endblock %} 
Okay, I see some hands starting to pop up in the back of the room. I realize that I covered the 
placeholders for template variables with the double curly braces, but you haven\u2019t yet seen the Django 
template blocks. Django blocks in a parent template are spaces reserved for content in the child 
templates. So, if you create a template that inherits from base.html, you\u2019ll be able to specify a block in 
the child template called site_wrapper and put whatever content you would like into it. Whenever one 
of these children is rendered, the content of site_wrapper will be nested in your base.html template. 
Neat, huh? 
The first Django template block we\u2019ve defined, called title, contains some logic and variables for 
the corresponding tags in the head element of our site. We\u2019ll come back to the {% if %} Django 
template blocks later, but basically, they allow you to put logic in your templates the same way you 
would your code. Of course, the amount of actual logic you put in your template should be small. Even 
though Django templates come equipped to handle programming flow, they are intended to act as a thin 
presentation layer for your application. You should keep its use to a minimum to keep your templates 
simple and maintainable. 
In this case, our template is checking for the presence of a variable called page_title and if it\u2019s 
present, the template renders it before the name of the site, with a dash separating them. Make sure that 
the title block is only on one line, since line breaks will be included in the content of the tag. 
There are also two variables for meta keywords and meta description inside of