Login

Most bookmarked snippets

Snippet List

Template tag for stripping blank lines

When writing clean and easy-to-read templates, it's usually good to have structural template tags (e.g. {%for%}, {%if%}) alone on their own line with proper indentation. When such a template is rendered, the resulting HTML will have blank lines in place of the template tags. The leading blank space used for indentation is also intact. This template tag strips all empty and all-whitespace lines when rendering the template. Be careful not to apply it when not intended, e.g. when empty lines are wanted inside PRE tags.

  • template
  • html
  • strip
  • empty
  • blank
Read More

Unobtrusvie Foldable Admin Interface

Inspired by [snippet 550](http://www.djangosnippets.org/snippets/550/), this allows you to expand or collapse apps in the main Admin screen. Requires jQuery. If jquery.cookie.js is available it will remember which apps you have expanded. Recommended usage: Place the JavaScript in a file called `admin-expand.js`. Create `templates/admin/base_site.html` in your templates directory (which is also a good place to [brand your Admin](http://djangobook.com/en/1.0/chapter06/#cn70)). Put the following code near the top, and you're done (adjusting file paths as needed). {% extends "admin/base.html" %} {% block extrahead %} <script type="text/javascript" src="jquery-latest.js"></script> <script type="text/javascript" src="jquery.cookie.js"></script> <script type="text/javascript" src="admin-expand.js"></script> {% endblock %}

  • admin
  • jquery
Read More

Django Model Inheritance

This snippet shows an alternative and interesting way to do Model Inheritance in Django. For description of the code, follow the inline comments.

  • model
  • inheritance
Read More

Little middleware that create a facebook user

**How to use**: 1. Install [**PyFacebook** package](http://wiki.developers.facebook.com/index.php/PythonPyFacebookTutorial). 2. After make all steps in tutorial above, put this code in your app's models.py module (you maybe prefer split it and put the middleware class in some other file). 3. Put the FacebookUserMiddleware python-path in the MIDDLEWARE_CLASSES in your settings.py (after facebook.djangofb.FacebookMiddleware). You probably will add some fields to FacebookUser model class :)

  • middleware
  • user
  • facebook
Read More

Select multiple using a manytomany checkbox

Usage: from yourapp.fields import CheckBoxManyToMany from django.db import models class Weekday(models.Model): name = models.CharField() def __unicode__(self): return self.name class EventWithWeekday(models.Model): weekdays = CheckBoxManyToMany(Weekday)

  • checkbox
  • multiple
  • oldforms
  • select
Read More

Recaptcha with Django Comments

Working off b23's [recaptcha support](http://www.djangosnippets.org/snippets/433/), I have hacked a way to add recaptcha support using existing comments. I am sure there is a better way, and ultimately I will suggest a patch to add captcha support as an option, but for now I hope this helps. For a more detailed rundown (as well as a working sample), check out my [blog entry](http://nikolajbaer.us/blog/recaptcha-django-free-comments/).

  • comments
  • recaptcha
Read More

Pagination for date-based views

Date-based generic views do not provide pagination by default but Django is very extensible. It provides a Paginator that takes care of pagination. Since date based views usually order by descending order ie from latest entry to the oldest, I used a queryset to order the items (on a field called 'date_pub') and then pass this queryset to the paginator which takes care of the pagination.

  • views
  • date
  • pagination
Read More

Template tag: Extend with parameters

Extended extends tag that supports passing parameters, which will be made available in the context of the extended template (and all the way up the hierarchy). It wraps around the orginal extends tag, to avoid code duplication, and to not miss out on possible future django enhancements. Note: The current implementation will override variables passed from your view, too, so be careful. Some of the argument parsing code is based on: http://www.djangosnippets.org/snippets/11/ Examples: {% xextends "some.html" %} {% xextends "some.html" with title="title1" %} {% xextends "some.html" with title="title2"|capfirst %}

  • template
  • templatetag
  • extends
  • parameters
Read More

Extended Paginator

Generate a list of page links like: First Prev 1 2 3 *4* 5 6 7 Next Last To use: 1. Put Paginator.py into your app directory 2. Copy pagination.html to your templates directory 3. pass a paginator object to your Context 4. include the pagination.html template on the page you wanted paginated Feel free to send ideas for improvement. If enough people ask, I'll package this as a single app and perhaps even make the template inclusion into a templatetag for even easier use.

  • pagination
  • paginator
  • paging
  • pager
Read More

Using reverse() to do redirects

When I initially set up my blog, I put together the archives with URL patterns like so: * `/weblog/2007/` goes to `archive_year` * `/weblog/2007/08/` goes to `archive_month` * `/weblog/2007/08/24/` goes to `archive_day` * `/weblog/2007/08/24/some-slug` goes to `object_detail` The same patterns held for links, only the prefix was `/links/` instead of `/weblog/`. For a forthcoming redesign/rewrite, I'm switching to using abbreviated month names (e.g., "aug", "sep", "oct", etc.) in the URLs, which means I need to redirect from the old-style URLs to the new. This snippet is the solution I hit upon. Two things are notable here: 1. Each one of these views uses [reverse()](http://www.djangoproject.com/documentation/url_dispatch/#reverse), called with the appropriate arguments, to generate the URL to redirect to. This means URLs don't have to be hard-coded in. 2. Each view takes an argument -- `object_type` -- which is used to generate the view name to pass to `reverse`, meaning that only one set of redirect views had to be written to handle both entries and links. This is just one of many handy tricks `reverse` can do :)

  • urls
  • reverse
  • redirects
Read More

page_link

To make page links like below: Prev 1 ... 23 24 25 26 27 ...221 Next Use like this , "bbs_posting_list" is the name of url {% page_link "bbs_posting_list" page pages %}

  • page
Read More

newforms: Add field-specific error in form.clean()

This is a bit of a hack, but as far as I can see currently the only way to specify a validation error that is specific to a field in form.clean(). I am aware of clean_<fieldname>, but those are difficult to use when the validation process for a field involves other fields as well, because the necessary data might at that point not be yet available in form.cleaned_data.

  • newforms
  • forms
  • validation
  • clean
Read More

DefaultValueWidget

Can be used if a form field should not be editable, but the current value or the value that will be automatically used should still be visible to the user. __init__ takes two additional parameters: **value** is the actual value to be used when saving the form, while **display** determines what is shown to the user when rendering. If *display* is not specified, *value* itself will be used instead. If *display* is a *ModelChoiceField*, *value* is assumed to be a primary key of the model, and the widget will automatically try to retrieve and use the string representation of the corresponding item.

  • newforms
  • forms
  • widgets
  • widget
Read More

Partial OpenID provider implementation from idproxy.net

Lots of people have asked me when the [django-openid](http://code.google.com/p/django-openid/) package will provide tools for running an OpenID provider (in addition to an OpenID consumer). The answer is "when it's done", but since it's such a common request I've decided to post some example code to help people who want to work it out for themselves. This is the openidserver.py file from [idproxy.net](http://idproxy.net/). It is **incomplete** - the urlconf, models, templates and some utility functions are not included. In other words, it's useless for anything other than providing a few hints as to how you can go about implementing a provider. Nonetheless, it's better than nothing. I hope this will prove a useful example for people trying to figure out how to best integrate the JanRain Python OpenID library with Django to build an OpenID provider.

  • openid
  • incomplete
  • partial
Read More

Form rendering using a template instead of builtin HTML

As an alternative to using forms rendered with the default hard-coded html, this factory function will take a template name as argument, and return a Form class based on django.newforms.BaseForm, which will render each form field using the supplied template. As an example, I'm using this class as follows in one project (slightly edited with respect to project and app names): # Get a form class which renders fields using a given template CustomForm = proj.utils.makeTemplatedForm(template="app/formfield.html") # Get base form class for the details model BaseAppForm = forms.form_for_model(models.AppDetail, form=CustomForm) using this template: {% if errors %} <ul class="errorlist"> {% for error in errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} {% if field.required %}<span class="required">*</span>{% endif %}{{ text }} {{ help_text }}

  • template
  • newforms
  • rendering
Read More

3110 snippets posted so far.