Login

Most bookmarked snippets

Snippet List

Middleware to remove the WWW from the URL

Works like the [PREPEND_WWW](http://www.djangoproject.com/documentation/settings/#prepend-www) setting but, instead of adding, it removes the www. Usage: In the settings file add the UrlMiddleware to the middleware list and set REMOVE_WWW = True

  • middleware
Read More

Raise Exception on invalid template variable

This recipe raises an exception if there is an invalid variable in the template. See [#6766](http://code.djangoproject.com/ticket/6766) Note: I don't need this snippet any more, since I don't use the template language any more. For my projects using only python is better (complex logic, simple layout).

  • template_string_if_invalid
Read More

Newforms field for decimals with a comma

This might be handy in countries where decimals are entered with a comma separating the decimal places from the integer part (for instance in Germany). It lets user enter and displays all decimals with a comma separator. I ran into this problem and couldn't find a clean internationalized way of doing it... but newforms makes it so easy to roll your own. Hope it helps someone.

  • newforms
  • locale
  • comma
  • decimal
Read More

Augmented TimeField

A TimeField that lets you parse a wide variety of freeform-text time descriptions. This doesn't inherit from TimeField because it doesn't use any of its functionality. Includes unit tests demonstrating some examples of what the parser will and won't handle.

  • newforms
  • timefield
Read More

Scoped Cache Compatible with Django Caching Helpers

Have you ever felt the need to run multiple Django projects on the same memcached server? How about other cache backends? To scope the cache keys, you simply need to prefix. However, since a lot of Django's internals rely on `django.core.cache.cache`, you cannot easily replace it everywhere. This will automatically upgrade the `django.core.cache.cache` object if `settings.CACHE_PREFIX` is set to a string and the Middleware contains `ScopeCacheMiddleware`. A thread discussing the merging of this functionality into Django is available on [the dev mailing list](http://groups.google.com/group/django-developers/browse_thread/thread/d45edaafec56da2a). However, (as of now) nowhere in the thread does anyone mention the reason why this sort of treatment is needed: Many of Django's internal caching helpers use `django.core.cache.cache`, and will then conflict if multiple sites run on the same cache stores. Example Usage: >>> from django.conf import settings >>> from django.core.cache import cache >>> from scoped_caching import prefix_cache_object >>> settings.CACHE_PREFIX 'FOO_' # Do this once a process (e.g. on import or Middleware) >>> prefix_cache_object(settings.CACHE_PREFIX, cache) >>> cache.set("pi", 3.14159) >>> cache.get("pi") 3.14159 >>> cache.get("pi", use_global_namespace=True) >>> cache.get("FOO_pi", use_global_namespace=True) 3.14159 >>> cache.set("FOO_e", 2.71828, use_global_namespace=True) >>> cache.get("e") 2.71828 To Install: Simply add `ScopeCacheMiddleware` as a middleware and define `settings.CACHE_PREFIX` and enjoy!

  • middleware
  • cache
  • namespace
Read More

HTML Widgets

A simple widget library to provide HTML4 widgets for HTML validation fanatics.

  • html
  • widget
  • html4
Read More

SimpleMachines forum authentication backend

Authentication backend for Simple Machines Forum user database. Needs one setting in `settings.py`: SMF_PREFIX = 'smf' This is prefix of SMF tables. This shippet assumes that they are in the same database. There is one more optional setting: SMF_GROUP = 1 If set, will allow only users from group with given id. May be used to allow access to admin page only for moderators.

  • authentication
  • backend
  • smf
Read More

Age - custom filter

Based on the discussion at Empty Thoughts (http://blog.michaeltrier.com/2007/8/6/age-in-years-calculation) I built a quick and dirty custom filter. Save this as a file in your "templatetags" folder. I called mine "calculate_age.py" and then in your template "{% load calculate_age %}" then use it, "{{ object.birthdate|age }}"

  • filter
  • age
  • birthday
  • custom-tag
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 `®` for ®, for example.

  • escape
  • htmlentities
  • ascii
Read More

Template tags/filter for working with query strings

Some template tags/filter for working with query strings in templates. Examples: {% load qstring %} {% qstring %} # Prints current request's query string {% qstring as current_qstring %} # Same but goes to context {{ current_qstring|qstring_del:"key1" }} # Deletes all key1 values {{ current_qstring|qstring_del:"key1&key2" }} # Deletes all key1 and key2values {{ current_qstring|qstring_set:"key1=1&key2=2" }} # Deletes all old key1 and key2 values and adds the new values.

  • templatetag
  • string
  • query
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

OwnerField

This is a little helper for associating an owner to a newly created object, in this case making the assumption that the current user is always the owner. It removes the necessity of adding a custom save hook to your model. get_current_user comes from this middleware trick to cache the current user: http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser

  • model
  • user
  • field
  • owner
  • ownerfield
Read More

PreSaveMiddleware

With this middleware in place (add it to the MIDDLEWARE_CLASSES in your settings) you can pass a request to the model via a pre_save method on the model. I'm not sure if it is an improvement over the [threadlocals method] (http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser) but it may be an alternative that can be improved upon? class MyModel(models.Model): name = models.CharField(max_length=50) created = models.DateTimeField() created_by = models.ForeignKey(User, null=True, blank=True) def pre_save(self, request): if not self.id: self.created_by = request.user

  • middleware
  • pre_save
  • signals
Read More

3110 snippets posted so far.