Django

Cheatsheet

These are my notes on django. I have written them down here to document the process, and to avoid looking for this information myself each time I need it. At least, until I memorize everything :D

If you find them useful, great. If you find an error, do let me know! But please understand this is not a django tutorial. There are better places for that!

Create project

bash django-admin.py startproject mysite

Start development server

bash cd mysite python manage.py runserver Alternatives bash python manage.py runserver 8080 python manage.py runserver 0.0.0.0:8000 # listen on all IP's

settings.py

To use postgresql


DATABASES['default']['engine'] = 'django.db.backends.postgresq_psycopg2l'

London's timezone:


TIME_ZONE = 'Europe/London'

Create required tables


python manage.py syncdb

If it's the first time, it'll create tables for auth, session, etc... and also will ask for an admin user.

Create an app


python manage.py startapp app_name

Edit app_name/models.py and add the definition for your models. They inherit from django.db.models.Model and have fields with different data types.

It's nice to have a unicode method on the models so you get a nice representation when printing them:


def __unicode__(self):
        return self.field

To use django's user model as foreign key for your models, in models.py:


from django.contrib.auth.models import User

# and use that User as ForeignKey for example:

class MyClass(models.Model):
        title = models.CharField(max_length=100)
        user = models.ForeignKey(User)

Add app_name to the list of INSTALLED_APPS in settings.py.

To generate the sql that wouldl create the tables for the models of your app:


python manage.py sql app_name

and


python manage.py syncdb

would actually create the tables in the database.

Interactive shell


python manage.py shell

And there:


from app_name.models import MyModel
# list current MyModels
MyModel.objects.all()

# create new MyModel
m = MyModel(first_field='value', second_field='new value')
m.save()

# return object with id = 1
MyModel.objects.filter(id=1)

# etc etc :)

Activate the admin site

Add "django.contrib.admin" to INSTALLED_APPS in settings.py

Run the manage script again:


python manage.py syncdb

Edit app_name/urls.py


# uncomment these lines
from django.contrib import admin
admin.autodiscover()

# and this one
(r'^admin/', include(admin.site.urls)),

Make your application's models modifiable in the admin

Create a file called admin.py in your app_name directory, and edit it to look like this: python from app_name.models import MyClass from django.contrib import admin admin.site.register(MyClass) And restart the server. There should be options for editing/managing the models in the admin area now, for free!

Customizing the admin views

Instead of simply invoking admin.site.register(MyClass), we'll define a MyClassAdmin class in the same file, and pass it as the second parameter to register. Like this:


class MyObjectAdmin(admin.ModelAdmin):
        # use the title and url fields for listing the models in the admin
        list_display = ('title', 'url')

admin.site.register(Feed, FeedAdmin)

Setting templates directory

The manual suggests to use an absolute directory, but that's not very portable. To use a relative one, just use python! ;)

In settings.py:


# add this at the beginning of the file
import os
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))

# and add the directory to TEMPLATE_DIRS
TEMPLATE_DIRS = (
        # this adds the templates folder in your project to the list of template dirs
        os.path.join(PROJECT_PATH, 'templates') 
)

Trick by Nilesh. Thanks!

Customize the admin appearance

Replace 'Django administration' with something else

Copy django/contrib/admin/templates/admin/base_site.html to your site's TEMPLATE_DIRS as admin/base_site.html. Or in other words:


mkdir site_dir/templates/admin
cp django_dir/django/contrib/admin/templates/admin/base_site.html site_dir/templates/admin/base_site.html

And edit the copied file as required.

Same can be done with the rest of stock templates (copy and modify).

URLs

The 'master' file with urls is defined in settings as your project_name.urls:


ROOT_URLCONF = 'mysite.urls'

Tuple syntax: (regular expression, Python callback function [, optional dictionary])

In urls.py, URLs can be defined directly or nested (which includes other files with url settings):


(r'^polls/

<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
```python

urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

```python

urlpatterns = patterns('django.views.generic.date_based',
    (r'^

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
```python

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse


from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template


from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

python from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: python from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):


<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

Child:


{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops:


{% for item in collection %}
{{ item.field }}
{% endfor %}

Permalinks and named routes

In a model


@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):


url(r'^stuff/(\d+)/

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes:

{% url app_views.client client.id %}`

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:


if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.

More concise way:


from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:


import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))

Then it's possible to do this:


{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/

or

```python
url(r'accounts/login/ (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

```html

{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py:


url(r'accounts/logout/, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>,'archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'tag'), )



<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'my_app.views.mymodel_view', name='mymodel_view'),



When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>,'archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'tag'), )



<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'django.contrib.auth.views.login'),`

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'django.contrib.auth.views.login', name='accounts_login'),

(more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'django.contrib.auth.views.logout', name='accounts_logout')

, 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'django.contrib.auth.views.login', name='accounts_login'),

(more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'article_detail'), # guess what? )



<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') ,'archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'tag'),
)

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'polls.views.index'),
(r'^admin/', include(admin.site.urls)),

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)),



<h3>Pattern syntax, capturing</h3>

When a line (pattern) matches, a view is invoked and the matches are sent to it.


<h3>Common prefixes</h3>
<code lang="python">
urlpatterns = patterns('news.views',
    (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive
    (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what?
)
</code>

<h3>Concatenating urlpatterns</h3>

This is perfectly OK:

<code lang="python">
urlpatterns = patterns('django.views.generic.date_based',
    (r'^$', 'archive_index'),
    (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
)

urlpatterns += patterns('weblog.views',
    (r'^tag/(?P<tag>\w+)/$', 'tag'),
)
</code>

<h3>Including other URLconfs</h3>

These are the <em>nested</em> urls in app_name/urls.py. Each new urls.py file should roughly follow this structure:
<code lang="python">
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'yourpattern', 'the.view'),
)
</code>

Of course common prefixes and concatenating url patterns can both be done here.

<h2>Views</h2>

In app_name/views.py.

<h3>Simplest: HttpResponse</h3>

<code lang="python">
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)
</code>

<h3>Richest: with render_to_response, context and template</h3>

<code lang="python">
from django.shortcuts import render_to_response
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
</code>

<h3>Return 404's</h3>
<code lang="python">
from django.http import Http404
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})
</code>

A shortcut:
<code lang="python">
from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
</code>

<h3>Template inheritance</h3>

Parent template defines blocks that can be overriden by child templates.

Parent (base.html):
<code lang="html">
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
</code>

Child:
<code lang="html">
{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <h2>{{ entry.title }}</h2>
    <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
</code>

<h3>Quick template how-to</h3>

Output data: <code>{{ variable }} or {{ variable.field }}</code>

Item permalink: <code>{{ object.get_absolute_url }}</code> (if the object has defined that method!)

Loops:
<code>
{% for item in collection %}
{{ item.field }}
{% endfor %}
</code>

<h4>Permalinks and named routes</h4>

In a model
<code lang="python">
@models.permalink
def get_absolute_url(self):
        return('mymodel_view', str([self.id]))
</code>

'mymodel_view' is the name of the pattern that provides that model permalink in <strong>urls.py</strong> (note the url( at the beginning-- it's not just a raw pattern):

<code lang="python">
url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),
</code>

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: <code>{% url app_views.client client.id %}</code>

<h2>Users, authentication...</h2>

Official <a href="http://docs.djangoproject.com/en/dev/topics/auth/">documentation</a>.

<h3>Detecting if a user is logged</h3>

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the <em>user</em> property in <strong>request</strong>, like this:

<code lang="python">
if request.user.is_authenticated():
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
</code>

More concise way:

<code lang="python">
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...
</code>

If user is not logged in, he'll be redirected to <strong>settings.LOGIN_URL</strong>

In the templates, the user variable is defined if we use a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext">RequestContext</a> instead of just a Request in the views:

<code lang="python">
import django.template.RequestContext
# ...

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
</code>

Then it's possible to do this:

<code lang="python">
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
</code>

<h3>Logging in</h3>

The default value for <a href="http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_URL">settings.LOGIN_URL</a> is '/accounts/login'

It has to be defined in the <strong>urls.py</strong> file too.

<h4>Using django's login view</h4>

In <strong>urls.py</strong>:

<code lang="python">(r'^accounts/login/$', 'django.contrib.auth.views.login'),</code>

or

<code lang="python">url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'),</code> (more convenient for named routes in the templates)

Create the template <strong>registration/login.html</strong> with these contents:

<code lang="html">
{% extends "base.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>

{% endblock %}
</code>

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the <em>next</em> variable or, if <em>next</em> is not set, to settings.LOGIN_REDIRECT_URL (default = <em>/accounts/profile/</em>).

<h3>Logging out</h3>

In <strong>urls.py</strong>:
<code lang="python">
url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')
</code>, 'article_detail'), # guess what?
)

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout') , 'polls.views.index'), (r'^admin/', include(admin.site.urls)), `

Pattern syntax, capturing

When a line (pattern) matches, a view is invoked and the matches are sent to it.

Common prefixes

urlpatterns = patterns('news.views', (r'^articles/(\d{4})/$', 'year_archive'), # goes to news.views.year_archive (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), # goes to news.views.month_archive (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), # guess what? )

Concatenating urlpatterns

This is perfectly OK:

urlpatterns = patterns('django.views.generic.date_based', (r'^$', 'archive_index'), (r'^(?P\d{4})/(?P[a-z]{3})/$','archive_month'), )

urlpatterns += patterns('weblog.views', (r'^tag/(?P\w+)/$', 'tag'), )

Including other URLconfs

These are the nested urls in app_name/urls.py. Each new urls.py file should roughly follow this structure: from django.conf.urls.defaults import *

urlpatterns = patterns('', (r'yourpattern', 'the.view'), )

Of course common prefixes and concatenating url patterns can both be done here.

Views

In app_name/views.py.

Simplest: HttpResponse

from django.http import HttpResponse

def index(request): return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)

Richest: with render_to_response, context and template

from django.shortcuts import render_to_response from polls.models import Poll

def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

Return 404's

from django.http import Http404 def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render_to_response('polls/detail.html', {'poll': p}) A shortcut: from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})

Template inheritance

Parent template defines blocks that can be overriden by child templates.

Parent (base.html): <!DOCTYPE html>

{% block title %}My amazing site{% endblock %}

{% block content %}{% endblock %}

Child: {% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %}

Quick template how-to

Output data: {{ variable }} or {{ variable.field }}

Item permalink: {{ object.get_absolute_url }} (if the object has defined that method!)

Loops: {% for item in collection %} {{ item.field }} {% endfor %}

Permalinks and named routes

In a model @models.permalink def get_absolute_url(self): return('mymodel_view', str([self.id]))

'mymodel_view' is the name of the pattern that provides that model permalink in urls.py (note the url( at the beginning-- it's not just a raw pattern):

url(r'^stuff/(\d+)/$', 'my_app.views.mymodel_view', name='mymodel_view'),

When the admin site detects a get_absolute_url method in a model, it uses it to add a "View in place" link.

In templates, the url tag allows for outputting named routes: {% url app_views.client client.id %}

Users, authentication...

Official documentation.

Detecting if a user is logged

Make sure the MIDDLEWARE setting contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Then in the views you can use the user property in request, like this:

if request.user.is_authenticated():

# Do something for authenticated users.

else:

# Do something for anonymous users.

More concise way:

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

If user is not logged in, he'll be redirected to settings.LOGIN_URL

In the templates, the user variable is defined if we use a RequestContext instead of just a Request in the views:

import django.template.RequestContext

...

def some_view(request):

# ...
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Then it's possible to do this:

{% if user.is_authenticated %}

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

Logging in

The default value for settings.LOGIN_URL is '/accounts/login'

It has to be defined in the urls.py file too.

Using django's login view

In urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or

url(r'accounts/login/$', 'django.contrib.auth.views.login', name='accounts_login'), (more convenient for named routes in the templates)

Create the template registration/login.html with these contents:

{% extends "base.html" %}

{% block content %}

{% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% csrf_token %}
{{ form.username.label_tag }} {{ form.username }}
{{ form.password.label_tag }} {{ form.password }}

{% endblock %}

The view shows the form on GET and tries to log in on POST. If successful it redirects to the value of the next variable or, if next is not set, to settings.LOGIN_REDIRECT_URL (default = /accounts/profile/).

Logging out

In urls.py: url(r'accounts/logout/$', 'django.contrib.auth.views.logout', name='accounts_logout')