Login

Top-rated snippets

Snippet List

Automagically import settings from installed applications

Use this snippet at the end of your main settings.py file to automagically import the settings defined in each app of `INSTALLED_APPS` that begins with `APPS_BASE_NAME`. Set `APPS_BASE_NAME` to the base name of your Django project (e.g. the parent directory) and put `settings.py` files in every app directory (next to the `models.py` file) you want to have local settings in. # works in the Django shell >>> from django.conf import settings >>> settings.TEST_SETTING_FROM_APP "this is great for reusable apps" Please keep in mind that the imported settings will overwrite the already given and preceding settings, e.g. when you use the same setting name in different applications. Props to [bartTC](http://www.djangosnippets.org/users/bartTC/) for the idea.

  • settings
  • import
  • reusable
  • apps
  • applications
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

htmlentities

The built-in escape filter only works with certain characters. It works great in environments where you can declare your charset (UTF-8). However, not everything can handle anything outside of the ASCII charset. This replaces all non-ASCII characters with their encoded value as `&#174;` for ®, for example.

  • escape
  • htmlentities
  • ascii
Read More

Time ranges like 7-9 p.m.

Template filter to format a start and end time in to a range. Uses Django's ["P" format](http://www.djangoproject.com/documentation/templates/#now) and assumes start and end time are on the same day or night before/morning after. `{{ start_time|time_range:end_time }}` Examples: 7-8 p.m. 8 p.m. - midnight noon - 4 p.m. 9:45 a.m. - 5:15 p.m. 10:30 p.m. - 1:30 a.m.

  • format
  • time
  • range
Read More
Author: sgb
  • 3
  • 4

Stop tests at the first failure

**Note**: The `--failfast` argument in Django since version 1.2 does this. Use this snippet for earlier versions. If a large number of your unit tests get "out of sync", it's often annoying to scan through a large number of test failures which overflow the terminal window's scroll buffer. This library strictly stops after the first failure in a doctest suite. If you're testing multiple applications, it also stops after the first test suite with failures in it. So effectively you'll get one failure at a time. This code has been tested with doctests only so far. You can also fetch the latest source from [my repository](http://trac.ambitone.com/ambidjangolib/browser/trunk/test/).

  • testing
  • unittest
Read More

Decorating urlpatterns

One thing I wanted for a while was the ability to basically apply something like @login_required to a bunch of urlpatterns in one go, instead of having to decorate each and every view manually. In this example, the latter two views will always raise a 404.

  • urls
  • views
  • decorators
  • urlpatterns
Read More

ImageField with per user folder

If you need to upload Image files into folders qualified with user name eg.: 'images/user1/2008/01/01' then you may use this snippet. In order to use it you have to install ThreadLocals middleware as described here: http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser Then just import UserImageField class at your models.py and specify 'upload_to' parameter with '%(user)s' in the path eg.: ` image3 = UserImageField(_('Image 3'), upload_to='flower_images/%(user)s/%Y/%m/%d', null=True, blank=True) `

  • imagefield
  • path
Read More

Breadcrumbs for flatpages

Custom template filter to generate a breadcrumb trail for a flatpage. Say you have a series of flatpages with URLs like /trunk/branch/leaf/ etc. This filter looks at the URL of a given flatpage, figures out which of the leftwards text chunks correspond to other flatpages, and generates a string of anchored HTML. Usage: {% load make_breadcrumb_trail %} {{ flatpage.url|crumbs:flatpage.title }}

  • filter
  • templatetags
  • breadcrumb
  • flatpage
Read More
Author: jca
  • 3
  • 14

TableSelectMultiple Widget

A widget for selecting from a list of `Model` instances using `MultipleChoiceField` which renders a table row for each choice, consisting of a column for a checkbox followed by a column for each item specified in `item_attrs`, which must specify attributes of the objects passed as choices.

  • forms
  • table
  • widget
  • selectmultiple
Read More

Automate unique slugs

If you want unique values for a slug field, but don't want to bother the user with error messages, this function can be put into a model's save function to automate unique slugs. It works by appending an integer counter to duplicate slugs. The item's slug field is first prepopulated by slugify-ing the source field. If that value already exists, a counter is appended to the slug, and the counter incremented upward until the value is unique. For instance, if you save an object titled Daily Roundup, and the slug daily-roundup is already taken, this function will try daily-roundup-2, daily-roundup-3, daily-roundup-4, etc, until a unique value is found. Call from within a model's custom save() method like so: `unique_slug(item, slug_source='field1', slug_field='field2')` where the value of field slug_source will be used to prepopulate the value of slug_field. Comments appreciated!

  • slug
  • save
Read More

nginx x-accel-redirect protection of static files

This snippet requires nginx as your front end server (for serving static files) and any django enabled server as a backend that only gets the dynamic requests (I use apache with mod_python). If you have no idea what I'm talking about, you probably won't need this snippet. I previously tried something [similar](http://www.djangosnippets.org/snippets/62/) just using mod_python, but this was too unstable for my needs (the PythonAuthenHandler seems to be called multiple times for no apparent reason). The patch from that snippet was also used as a base for [this ticket](http://code.djangoproject.com/ticket/3583). This is part of an authentication mechanism I use for protecting static files. Nginx has the so called x-accel-redirect feature, that tells nginx to serve an internal (read 'protected') file if the backend response has the ['X-Accel-Redirect'] header set. No other headers are touched, but by deleting all relevant headers in the default django response, nginx will create those headers for us. The usage is pretty simple: * set up nginx as a proxy for apache + mod_python + django (google for this if you don't know how) * configure nginx as shown in the code snippet (for testing leave out the internal part to see if the files are accessible) * configure your urls.py to point to the validation view * make your sites hrefs point to the view instead of the file directly (those real urls will be completely hidden from your visitors) * Done!

  • authentication
  • nginx
Read More

Manager for something like __inall

Provides the method from_related_ids, which lets you select some objects by providing a list of related ids (The huge difference to __in is that the objects have to match al of the ids, not only one) Model Example:: class Article(models.Model): text = models.TextField() tags = ManyToManyField('Tag') objects = AllInManager() Usage:: Article.objects.from_related_ids((1,2,3,4), 'tags')

  • model
  • db
  • manager
Read More

xmlrpc basic auth

decorator which performs basic http auth authentication against the known userbase. This decorator is only for xml-rpc services. When there is no basic auth a proper response will be returned

  • auth
  • xmlrpc
Read More

bigger textfields in admin panel

Sometimes a textarea field is to small for usage. I add some JavaScript and CSS to resize all textareas a little dynamically: The JS change the size in dependence text-lengthen. You should store this snippet into a file like this: templates_django/admin/base_site.html

  • admin
  • textfield
  • admin-panel
Read More

3110 snippets posted so far.