Login

Top-rated snippets

Snippet List

Boxes as template tags

It's a template tag used to create boxes with nested divs (useful to keep the templates DRY). For example: {% menubox titlevar %} Content here {% endmenubox %} will generate the html with the nested divs div class=box div class=box-outer div class=box-inner Headline Content /div /div /div [more detail on this blog post](http://pedro.valelima.com/blog/2007/sep/26/boxes-template-tags/)

  • template-tag
  • box
Read More

Smart append slash middleware

This middleware replaces the behavior of the APPEND_SLASH setting in the CommonMiddleware. Please set `APPEND_SLASH = False` and `SMART_APPEND_SLASH = True` if you are going to use this middleware. In your URL patterns, omit the trailing slash for URLs you want accessible without the slash. Include the slash for those URLs you wish to be automatically redirected from an URL with the slash missing. If a URL pattern exists both with and without a slash, they are treated as two distinct URLs and no redirection is done. Example urlpatterns = patterns('some_site.some_app.views', (r'^test/no_append$','test_no_append'), (r'^test/append/$','test_append'), (r'^test/distinct_url$', 'view_one'), (r'^test/distinct_url/$', 'view_two'), ) Behavior of URLs against the above patterns with SMART_APPEND_SLASH enabled: http://some_site/test/no_append → test_no_append() http://some_site/test/no_append/ → 404 http://some_site/test/append → http://some_site/test/append/ http://some_site/test/append/ → test_append() http://some_site/test/distinct_url → view_one() http://some_site/test/distinct_url/ → view_two() This module is also available [in our SVN repository](http://trac.ambitone.com/ambidjangolib/browser/trunk/middleware/common.py).

  • middleware
  • url
  • slash
Read More

Another Memcache Status View

This was inspired by [this memcache status snippet](http://www.djangosnippets.org/snippets/54/) However, this version uses the quasi-internal cache._cache.get_status(), and it compiles a list of stats for each server that you specify in your CACHE_BACKEND setting.

  • memcache
Read More

XFN Form Field

**This is a newforms field for XFN relationships.** It normalizes input by removing excess whitespace, converting to lowercase and removing duplicates. This field also validates the relationship according to the [XFN profile](http://gmpg.org/xfn/11): `me` can only appear by itself and, at most, one value from each of the family, friendship and geographical categories is allowed. The `XFN_*` constants would probably be imported from somewhere else in practice, but are included here for simplicity.

  • newforms
  • fields
  • forms
  • form
  • field
  • xfn
Read More

Convert Unicode to ASCII

Unicode is great, but there are places where the conversion ends up with unintelligible characters. I first noticed this with curly quotes entered in forms on our site. `unicode_to_ascii` converts compound characters to close approximations in ASCII: such as umlaut-u to u, 1/2 (fraction glyph) to 1/2. You can add additional mappings in CHAR_REPLACEMENTS.

  • unicode
  • ascii
  • convert
Read More

Make anything into a template

This is a quick and dirty way to reuse the Django templating system for your own ends. Just pop in the familiar Django template syntax into whatever content you like and any chunk of content can be a template. This is great if you need to wrap data in HTML (as in for a mass email). The best part about this is that your "template" can now be stored in a database, instead of just in the file system.

  • template
  • templating
Read More

A custom 500 handler which is AJAX-aware

The default 500 handler does not take into consideration if the HTTP request made is an XMLHttpRequest. If it's an XHR, then it may not be a good idea to send back your default 500 HTML page. To use this custom 500 handler, just add the following to your urls.py: handler500 = 'my_project.my_app.views.my_500'

  • ajax
  • 500
  • handler
  • httprequest
Read More

newforms and ModelForm

I noticed that form_for_* in newforms now carry deprecation warnings. This code is a minimal demonstration of how to use ModelForm as a replacement. Full information can be found on [Stereoplex](http://www.stereoplex.com/two-voices/django-modelform-and-newforms). Hope this helps you.

  • newforms
  • form_for_instance
  • modelclass
  • form_for_class
  • deprecated
Read More

Field map for models

It seems like one way or another I always need to get access to a specific field of a Model object. The current way to do this is to iterate through the object's _meta.fields list, comparing with the `name` attribute. Why not just have a lookup of fields? If you paste this code at the bottom of your models.py file it will add a `field_map` attribute to the meta options. For example: `profile = User.objects.get(id=1).get_profile()` `upload_to = profile._meta.field_map['image_icon'].upload_to` ...

  • models
  • fields
  • meta
Read More

packjs templatetag

Based on jspacker by Dean Edwards, Python port by Florian Schulze: http://www.crowproductions.de/repos/main/public/packer/jspacker.py Packs javascript Example usage:: {% packjs %} var a = 1; var b = 2; var c = 3; alert(a+b); {% endpackjs %} This example would return this script:: eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[c]=k[c]||c;k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp("\\b"+e(c)+"\\b","g"),k[c]);return p}('0 5 = 1;\n 0 4 = 2;\n 0 7 = 3;\n 6(5+4);\n',8,8,'var||||b|a|alert|c'.split('|'),0,{}))

  • templatetag
  • javascript
  • pack
Read More

Mathematical Captcha

Simple mathematical captcha where human is asked to solve a simple mathematical calculation like 2+3=?. Don't require database access or external libraries like PIL. To use MathCaptchaForm subclass it and add your fields. For example of usage and discussion about security of this captcha comparing with traditional image captcha please see my blog entry [Improved Mathematical Captcha](http://www.mysoftparade.com/blog/improved-mathematical-captcha/)

  • captcha
Read More

NewForms Readonly / Edit Pattern

This is a little base class that I use to display forms in a readonly mode. Providing a simple javascript on the front end to allow a user to click an **edit** link that will show/hide the actual form. To use it simply inherit from it. Then in your templates do the following: `{{ form.as_readonly_table }}` **Other Notes** * **form.html** `{% for field in bound_fields %} {% include "newforms/field.html" %} {% endfor %}` * **field.html** `{% if field.errors %} <tr> <td>&nbsp;</td> <td>{{ field.errors }}</td> </tr> {% endif %} <tr> <th style="text-align:right"> <label for="id_{{ field.name }}">{{ field.label }}{% if field.field.required %}<span class="required"><sup>*</sup></span>{% endif %}</label> </th> <td>{{ field }} {% if field.help_text %} <p class="helptext">({{ field.help_text }})</p> {% endif %} </td> </tr>`

  • template
  • newforms
  • readonly
  • edit-mode
Read More

blocksetter

Sometimes you need to set a little bit more complex variable in the template (e.g. Title), that is being used more than once. this simple tag defines "blockset" tag. {% blockset variable-name %}{%endblockset} everything inside body (between blockset/endblockset) is being assigned to the variable "variable-name". I have found this quite useful with translations, or setting the title, where you out several variables into one sentence. Drop me an email if you will find this useful.

  • templatetag
  • block
  • set
Read More

3110 snippets posted so far.