Login

Most bookmarked snippets

Snippet List

Custom Template Tag - No Translate

Forces Django not to translate built in template tags and filters. If you have a multi-lingual site but certain parts of it are not all translated, you can use this snippet to force Django to bypass translation on all template tags and filters so things like dates aren't randomly translated whilst everything else is not. For example: `{% notrans %}{{download.doc|filesizeformat}}{% endnotrans %}` This snippet including the filesizeformat template tag would not be translated. Mega thanks goes out to Dan Fairs for all his help on this!

  • translation
  • multi-lingual
  • custom-template-tags
Read More

Wrapper-function Pattern

This is an example how to create a wrapping function that can read all incoming arguments, do something with them and then call the original function. This pattern works well with generic views. Note that wrapper function accepts arguments in both ways: as a list of unnamed arguments and as a list of keyword-value pairs. A real-world example: def published_object_list(request, *args, **kwargs): arg_names = object_list.func_code.co_varnames params = dict(zip(arg_names, args)) params.update(kwargs) params['queryset'] = params['queryset'].filter(is_published=True) if request.is_ajax(): params['template_name'] = "ajax/" + params['template_name'] return object_list(request, **params)

  • view
  • function
  • wrapper
Read More

Add httponly to session cookie

Middleware to set "sessionid" (ou your session cookie) with httponly (see ["Django bug report"](http://code.djangoproject.com/ticket/3304)). To work, you need put it before "SessionMiddleware"

  • cookie
  • security
  • httponly
Read More

dict recurse template tag for django

Based on http://www.djangosnippets.org/snippets/592/, a simplified recurse template tag that will explore dict and list objects. Useful and straightforward for JSON documents (for instance from couchdb :p). Actual usage example: {% recursedict mydictionary %} <ul> {% loop %} <li>{% if key %}<b>{{ key }}</b>:&nbsp;{% endif %}{% value %}</li> {% endloop %} </ul> {% endrecurse %} The main tag syntax is "recursedict var" where var is your dictionary name. The "key" property will contain the current key, or None if the current value comes from a list (in other words the list (a, b, c) is handled like a very hypothetical {None: a, None: b, None: c} dictionary.) {% value %} will output the current value, or recurse if the value is a list, tuple or dict.

  • template
  • templatetag
  • json
  • dict
  • resurse
Read More

Subdirectory and subcontext include template tag with examples

In principle it's a DRY code of a template node that can be used for creating project-wide template-tags. These can be used to display conceptually common blocks in templates with applications specific looks and content. E.g.: 1. application-specific info message, 2. model instances details in the list context, 3. login messages like 'Please login or signup to [some app-dependent text]' with appropriate url's, 4. standard forms (e.g with same CSS classes, displayed with uni_form). The code is profusely commented so look it up for details. Basically, when you have your project-wide `SubIncludeNode` tag defined, then just define appropriately named templates in applications template subdirectories e.g. `'profiles/_show_item.html'`. ** Example usage: login or signup message ** Let's say we are editing template rendered by the view indicated by the pattern named 'project_list' in the 'projects' app: {# those are equivalent #} {% login_or_signup %} {% login_or_signup project_list %} {% login_or_signup "project_list" %} {# academic purposes direct sub_include usage #} {# those two includes are also equivalent if there is no template called '_login_or_signup.html' in the 'projects' subdirectory #} {% url acct_signup as signup_url %} {% url acct_login as login_url %} {% url project_list as next_url %} {% sub_include "_login_or_signup.html" %} {% include "_login_or_signup.html" %} {# and those two are also equivalent if there is a template called '_login_or_signup.html' in the 'projects' subdirectory #} {% sub_include "_login_or_signup.html" from "projects" %} {% sub_include "_login_or_signup.html" %} {# also equivalent include if there is no variable called 'projects' in tempalte's context #} {% sub_include "_login_or_signup.html" from projects %} {# those are examples of using custom subcontext #} {% url acct_signup as signup_url %} {% url acct_login as login_url %} {% sub_include "_login_or_signup.html" from "default" with login_url,signup_url,next_url="/welcome" %} {% sub_include "_login_or_signup.html" with login_url="/login",next_url="/welcome",signup_url="/signup" %} ** Mored advanced usage proposal ** Say you have an subclasses of some model from the original app in a separate extending apps. You want to display subclasses instances differently using the original app templates. In the original app you do not know what the set of subclasses is (as the original app is not aware of the extending apps). Subclassing the `SubIncludeNode` you can override the `default_subdir` method such that it returns the app label of a model instance that was passed as a argument of your tag. This way you just put templates like `_show_instance.html` in extending apps subdirectories and voila - you have implementation of the overrideable templates displaying appropriately details about the model subclass instances.

  • templatetag
  • templatetags
  • include
Read More

Dynamically maintain local_constants.py from South migration

Allows you to dynamically maintain a local_constants.py file from a migration tool like South. Example of usage: set_constant('/home/projects/sample/local_constants.py', 'STAMP_MW_ID', 42, 'Set from sample.0007_add_constants.py') More more information, see [Allows you to dynamically maintain a local_constants.py file from a migration tool like South. Example of usage: set_constant('/home/projects/sample/local_constants.py', 'STAMP_MW_ID', 42, 'Set from sample.0007_add_constants.py') More more information, see [http://menendez.com/blog/maintain-contants-through-south-data-migration/](http://menendez.com/blog/maintain-contants-through-south-data-migration/).

  • migration
  • data
  • south
Read More

Shortcuts to your code organized by type (views, models, admin, ...)

Sometimes, when you're working on improving one specific aspect of your site, it's easier to browse your code by type than by application. E.g. you want quick access to all admin.py files because you're improving or customizing your admin site across the board and not for a specific app. This little management command adds a shortcuts dir to your project root that contains a bunch of symlinks to your code, organized in subdirs by type of code. You'll have to put this in `/management/commands/make_shortcuts.py` under an app of your choice. Usage: `python manage.py make_shortcuts`. Don't forget to ignore the /shortcuts directory in your source code management software.

  • shortcut
  • utility
  • organization
Read More

Test if sessions are working

I wasn't sure if my setup supported sessions properly. This view helped me make sure. Usage: fill the inputs with text and make sure that these values traverse a couple of requests. If it doesn't work then maybe the session backend you've set is broken?

  • sessions
Read More

localsettings

I'm using this to store settings in a thread-safe manner on mod_wsgi multithread deployment. The idea is to import `from localsettings import localsettings` instead of doing `from django.conf import settings` and use it as you would use normal settings, with the difference that you can alter settings for the current thread with a middleware (think of altering SITE_ID). Warning: altering settings is not officially supported and can lead to thread problems.

  • settings
Read More

Type checking templatetag filters

It's often useful to be able to check the type of an object in templates. Most recently I used this to do some trickery in my forms for certain field types. These template filters allow you to match the type of an object or a field widget with a string. It returns True if it matches and False if it doesn't or there is an error. for example: {% if form|obj_type:'mycustomform' %} <form class="custom" action=""> {% else %} <form action=""> {% endif %} {% if field|field_type:'checkboxinput' %} <label class="cb_label">{{ field }} {{ field.label }}</label> {% else %} <label for="id_{{ field.name }}">{{ field.label }}</label> {{ field }} {% endif %}

  • templatetags
Read More

Possessive-aware unicode for models

For a model FK'd to a user or profile, you might want every instance of that thing to appear in your site and in the admin as say "Joe's bucketlist." But if Joe's name is Ross, you want "Ross' bucketlist", not "Ross's bucketlist."

  • model
  • unicode
  • possessive
Read More

RedirectedURLField

This field is similar to the standard URLField, except it checks the given URL for a HTTP 301 response (permanent redirect) and updates its value accordingly. For example: >>> url = RedirectedURLField() >>> url.clean('http://www.twitter.com/') >>> 'http://twitter.com/' In models: class TestModel(models.Model): url1 = RedirectedURLField('Redirected URL') url2 = models.URLField('Standard URL')

  • url
  • redirect
  • field
Read More

3110 snippets posted so far.