Login

Top-rated snippets

Snippet List

Easier prefix handling for forms

**autoprefixed** is a decorator for Form classes that simplifies prefix handling by storing it in a hidden field. Thus when the form is posted, the prefix can be extracted from the posted data instead of having to pass it explicitly when instantiating the form.

  • form
  • prefix
Read More

Dynamically change admin widgets at runtime

django-adminwidgetswap =============== adminwidgetswap is used for dynamically swapping out widgets from django's generated admin. This allows applications to be packaged generically without the need for WYSIWYG dependencies editors- giving the application consumer the freedom to chose admin widgets without modifying original app source. Author ====== [David Davis](http://www.davisd.com) (http://www.davisd.com) [dynamically change django admin widets at runtime (django-adminwidgetswap) blog post](http://www.davisd.com/blog/2010/04/17/dynamically-change-django-admin-widgets-at-runtime/) Usage =============== To change a widget in django's admin, just put adminwidgetswap.py on the python path, import adminwidgetswap.py and use: adminwidgetswap.swap_model_field(model, field, widget) ...to change a widget for a direct model admin's field --- adminwidgetswap.swap_model_inline_field(model, field, widget) ...to change widgets for inlines of a specific model and field --- adminwidgetswap.swap_model_and_inline_fields(model, field, widget) ...to change both the widget for the direct model admin's field as well as all inline usages for the model and field --- I usually have a project-level application called website, and I put this initialization code inside the website app's __init__.py Usage - parameters =============== model is the Model class (eg. models.GalleryImage) field is the field name you're looking to swap (eg. 'image') widget is the widget you're going to swap for (eg. widgetlibrary.ThumbnailWidget())

  • admin
  • widgets
  • abstraction
Read More

immitating 'real' post_syncdb signal

I did not like the idea of having to load fixtures by creating a huge initial_data.json file. I also did not want to store my initial data in a bunch of <modelname>.sql files. Django has post_syncdb signal which fires when model(s) for an application are installed, but I needed something that would run only *once* at the end of syncdb command, at least after all of the models are installed, and here's what I've come up with. The code basically checks if the current callback is for the last app in your INSTALLED_APPS, and if so, executes some fixture loading code.

  • signals
  • post_syncdb
Read More

Excel Date

This allows you to just call excel_date and it will convert any dates between excel and python datetime.

  • date
  • excel
Read More

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

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

RML2PDF with Django

This is a django view that can return a PDF made using rml2pdf from reportlab. This RML is written with django templating system, to view the rml code and download a fully working version visit [reportlab](https://www.reportlab.com/software/documentation/sample-projects/rml-with-django/)

  • django
  • pdf
  • rml
  • reportlab
Read More

FloatField with safe expression parsing

This FloatField replacement allows users to enter math expressions, such as: 4/5 + sqrt(32) And will evaluate them safely when the field's clean() function is called. In the example above, it will evaluate to a float value of about 6.457. Reference: [http://lybniz2.sourceforge.net/safeeval.html](http://lybniz2.sourceforge.net/safeeval.html) The available functions are listed herein. Note that the from __future__ import division causes integer division expressions to be evaluated as floats. For example "1/2" evaluates as 0.5 when it would otherwise have evaluated to 0 (assuming Python 2.X).

  • fields
  • forms
  • parser
  • math
  • eval
  • parsing
  • floatfield
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

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

3110 snippets posted so far.