Chapter 3. Building a Pastebin. -------------------------------- URL configuration - entry points: ================================= We have already noticed urls.py in our project. This controls our website's points of entry. All incoming urls will be matched with the regexes in the ``urlpatterns`` and the view corresponding to the first match will get to handle the request. A request url that does not match any urlconf entry will be 404'ed. .. note:: brush up regexes in python from `python docs `_ or `diveintopython `_ As an example from our previous app: .. literalinclude:: djen_project/urls.py Now when we call http://127.0.0.1:8000/admin/ django matches that to the first regex. This urlconf has included ``admin.urls`` which means that all further regex matches will be done with the ``admin.urls`` module. Once again, the first match will get to handle the request. You can think of this as 'mounting' the admin app at ``/admin/``. You are of course free to change the 'mount point' to anything else you like. A typical urlconf entry looks like this:: (r'', , ), ``regex`` is any valid python regex that has to be processed. This would be absolute in the project urls.py and relative to the mount point in an app's urls.py ``view_function`` is a function that corresponds to this url. The function **must** return a ``HttpResponse`` object. Usually, shortcuts such as ``render_to_response``, are used though. More about views later. ``arg_dict`` is an optional dict of arguments that will be passed to the ``view_function``. In addition, options can be declared from the url regex too. For example:: (r'^object/?P(\d+)$', 'objects.views.get_object'), will match all urls having an integer after ``object/``. Also, the value will be passed as ``object_id`` to the ``get_object`` function. Named urls: +++++++++++ Usually, we would want an easier way to remember the urls so that we could refer them in views or templates. We could *name* our urls by using the ``url`` constructor. For example:: url(r'^welcome/$', 'app.views.welcome', name='welcome'), This line is similar to the previous urls, but we have an option of passing a ``name`` argument. To get back the url from its name, django provides: * ``django.core.urlresolvers.reverse`` function for use in views * ``url`` templatetag for use in templates We will see how to use the templatetag in our templates. .. note:: Also see http://agiliq.com/books/djangodesignpatterns/urls.html#naming-urls Grouped urls: ++++++++++++++ Sometimes, we would want to group together logically related urls. Or just avoid writing the full function path over and over. We can do this by putting the common path to the view function in the first argument of urlpatterns:: urlpatterns = patterns('', (r'^$', 'django.views.generic.create_update.create_object', { 'model': Paste }), ) and:: urlpatterns = patterns('django.views.generic.create_update', (r'^$', 'create_object', { 'model': Paste }), ) are equivalent. Templates - skeletons of our website: ====================================== You must be wondering where all those pages came from, since we have not touched any html yet. Well, since we used the admin app, we were able to rely on the admin templates supplied with django. A template is a structure of webpage that will be *rendered* using a *context* and returned as response if you want it to. A ``django.template.Template`` object can be rendered using the ``render`` method. Normally templates are html files with some extra django content, such as templatetags and variables. Note that our templates need not be publicly accessible(in fact they shouldn't be) from a webserver. They are not meant to be displayed directly; django will process them based on the request, context etc and respond with the rendered templates. In case you want a template to be directly accessible (e.g. static html files), you could use the ``django.views.generic.simple.direct_to_template`` generic view. Template Loaders: +++++++++++++++++ Django will usually look for templates in ``TEMPLATE_DIRS`` of settings.py and inside ``templates`` directory of each app. This is because of the ``TEMPLATE_LOADERS`` in the default settings.py:: # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) These functions fetch the template based on a given template path. To let django locate your ``hello_world.html`` you would have to place it in ``/templates`` or place it in any directory and set the ``TEMPLATE_DIRS``:: TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) to the absolute path of that directory. Context: ++++++++ A context is a dict that will be used to render a page from a template. All context keys are valid template variables. To display a user name in your template, suppose you provide the ``username`` in your context, you could do: .. sourcecode:: django Hello {{ username }} When this template is rendered using (e.g. using ``render_to_response``), ``username`` will be replaced with its value You can pass any variable to the context, so you can call a dict's key, or an objects property. However you cannot pass any arguments to the property. For example: .. sourcecode:: django Hello {{ user.username }} can be used to get ``user['username']`` or ``user.username`` Similarly: .. sourcecode:: django {{ user.username }} can be used to get ``user.get_absolute_url()`` Templatetags: +++++++++++++ Templatetags are helpers to the template. Suppose you have an ``iterable`` with a list of objects in your context: .. sourcecode:: django {% for object in objects %} {{ object }} {% endfor %} would render them. If this is a html template, we would prefer: .. sourcecode:: django {% if objects %}
    {% for object in objects %}
  • {{ object }}
  • {% endfor %}
{% endif %} which would render the objects in html unordered list. Note that ``{% if %}`` ``{% for %}`` ``{% endif %}`` ``{% endfor %}`` are all built-in templatetags. If and for behave very much like their python counterparts. Common templatetags and template inheritance: ++++++++++++++++++++++++++++++++++++++++++++++ Some templatetags we will use in our application: * ``url`` This templatetag takes a named url or view function and renders the url as found by ``reverse`` For example: .. sourcecode:: django View All would output .. sourcecode:: html View All It also takes arguments: .. sourcecode:: django {{ paste }} would output .. sourcecode:: html Sample Paste .. note:: You must make sure the correct urlconf entry for the give url exists. If the url entry does not exist, or the number of arguments does not match, this templatetag will raise a ``NoReverseMatch`` exception. * ``csrf_token`` This is a security related tag used in forms to prevent cross site request forgery. * ``include