Django Quickies

Debugging in templates

<pre>{% debug %}</pre>

<pre>errors
{{ form.error_dict|pprint }}</pre>

<pre>data
{{ form.data|pprint }}</pre>

Example of Edit Inline

models.py

class Poll(models.Model):
    question = models.CharField(maxlength = 200)

class Choice(models.Model):
    poll = models.ForeignKey(Poll, edit_inline=models.STACKED, num_in_admin=3)
    choice = models.CharField(maxlength = 200, core = True)
    votes = models.IntegerField(core = True)

urls.py

urlpatterns = patterns('',
    [...]
    (r'^poll_update/(?P<object_id>d+)/$', 'django.views.generic.create_update.update_object', {'model': Poll})
)

templates/myapp/pollform.html

{% extends "base.html" %}
{% block content %}

<pre>errors
{{ form.error_dict|pprint }}</pre>
<pre>data
{{ form.data|pprint }}</pre>

<p>Today's question is: <em>{{ object.question }}</em></p>

<form method="POST" action="./">

     <label for="id_question">Question:</label>{{ form.question }}

       {% for the_choice in form.choice %}
        {{ the_choice.id }}

        <TABLE>
        <TH><label for="id_choice.{{ forloop.counter0 }}.choice">Choice
        <TD>{{ the_choice.choice }}
        <TH><label for="id_votes.{{ forloop.counter0 }}.votes">Votes
        <TD>{{ the_choice.votes }}
        </TABLE>
   {% endfor %}

    <input type="submit" />
</form>

{% endblock %}

Send Emails

views.py

from django.core.mail import send_mail

send_mail('Subject here', 'Here is the message.', 'from@domain.com',
    ['to@domain.com'], fail_silently=False)

settings.py

EMAIL_HOST = 'domain.com'
EMAIL_PORT = '25'
EMAIL_HOST_USER = 'username'
EMAIL_HOST_PASSWORD = 'xxxxxxxx'

Generate RSS

from django.conf import settings
from django.utils import feedgenerator
from nm.models import Newsitem
import os

def generate_rss(self):

    file_name = "latest_news.rss"
    file_path = os.sep.join([settings.MEDIA_ROOT, file_name])
    file_url = os.sep.join([settings.MEDIA_URL, "site_media", file_name])

    feed = feedgenerator.Rss201rev2Feed(
        title=u"Newsmemory",
        link=file_url,
        description=u"Dernières nouvelles",
        language=u"fr",
    )

    qs = Newsitem.objects.select_related().filter(...)[:50]

    for r in qs:
        text = "<br />".join([r.source.name, "%s" % r.time, r.text])
        feed.add_item(title=r.title, link=r.get_absolute_url(), description="")

    fp = open(file_path, 'w')
    feed.write(fp, 'utf-8')
    fp.close()

Reuse Login / Logout

settings.py

INSTALLED_APPS = (
    'django.contrib.auth',
    [...]
)

urls.py

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

app_name/urls.py

(r'^accounts/profile/$', 'projectname.invoice.views.index'), # default page after login

templates/appname/registration/loggedout.html

templates/app_name/registration/loggin.html

{% block content %}

<div id="box"><h4>Login</h4></div>

{% if form.has_errors %}
<div id="alert">
    <p>Your username and password didn't match. Please try again.</p>
</div>
{% endif %}

{% if user.is_authenticated %}
<div id="alert">
    <p>You are already logged in as "{{ user }}".</p>
</div>
{% endif %}

<form method="post" action=".">
<P>
<table>
<tr><td><label for="id_username">Username:</label></td><td>{{ form.username }}</td></tr>
<tr><td><label for="id_password">Password:</label></td><td>{{ form.password }}</td></tr>
</table>
</P>
<p>
<input type="submit" value="Login" />
<input type="hidden" name="next" value="{{ next }}" />
</p>
</form>

{% endblock %}

Creating and Using Custom Filters

projectname/invoice/templatetags/

__init__.py
custom_filters.py

projectname/invoice/templatetags/custom_filters.py

from django import template
from django.conf import settings

def nop(value):
    return value[3:-4]

register = template.Library()
register.filter('nop', nop)

projectname/settings.py

INSTALLED_APPS = (
    'projectname.invoice'
)

projectname/templates/invoice/customer_detail.html

{% load custom_filters %}
{{ object.address|linebreaks|nop }}

Reuse Django Admin Widgets and Graphics

urls.py

urlpatterns = patterns('',
    [...]
     (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', {'packages': 'django.conf'}),
)

settings.py

ADMIN_MEDIA_PREFIX = '/media/'

template file

<script type="text/javascript" src="/jsi18n/"></script>
<script type="text/javascript" src="/media/js/core.js"></script>
<script type="text/javascript" src="/media/js/admin/RelatedObjectLookups.js"></script>
<script type="text/javascript" src="/media/js/calendar.js"></script>
<script type="text/javascript" src="/media/js/admin/DateTimeShortcuts.js"></script>

<img src="/media/img/admin/icon_changelink.gif">

Comments are closed.