Login

All snippets

Snippet List

Google map on admin address field

Who never wished to have valid address data by showing a little google map with a marker near the address input text ? Using js only it gets quite easy.

  • gmap
  • address
  • googlemap
Read More

Testing for failure in management commands

Because BaseCommand catches all CommandError exceptions and turns them into nicely formatted strings before calling sys.exit(1), it can be tricky to properly test failure. Normally, this is great, but it makes testing that a command fails when we expect to a little harder. That's where this snippet comes in. It redirects sys.stderr to an instance StringIO where we can monitor what's output and catches the BaseException raised by sys.exit(1). Form here, it's trivial to test that a management command fails exactly as you'd expect it to.

Read More

Run and cache only one instance of a heavy request

I have many heavy views which run slowly when accessed at same time in multiple threads. I make this decorator to allow run only one view at the time and cache returned result. Other threads will wait to complete first thread and use response from the cache if executed thread put it to cache. Also I take idea of MintCache to refresh staled cache and return cached (stale) response while response refreshed in the cache. Usage: @single_cacheable(cache_timeout=60, stale_timeout=30, key_template='my_heavy_view-{arg1}-{arg2}') def heavy_view(request, arg1, arg2): response = HttpResponse() ... your code here # cache timeout may be set from inside of view response._cache_timeout = cache_time return responce The "key_template" is a template for cache key. Some my views have additinal parameter "cache_time" which set from parent page and request.path is different for these pages but they need to be cached not depending of this parameter. Variable "key_template" in the example used named agrument, if you have no named paramaters you need to use 'my_heavy_view-{1}-{2}-{...}' where {1},{2}, {...} arguments of view. The line with setting "key" variable may be changed to: key = "sc_"+request.get_full_path() if you need to take full URL path as cache key.

  • cache
  • decorator
Read More

MultiSelect checkbox iterator template filter

Sometimes you want more rendering control than common widgets give you. We wrote this, for example, to allow rendering the checkboxes of a multi select field with checkbox widget, as multiple columns. Place this in the templatetags subdirectory of an app you are loading (be sure it has a __init__.py file), and load it something like this (you may want to shorten the name): {% load checkboxiterator_filter %} Then you can say something like: {% for checkbox in form.categories|checkboxiterator %} {# other code #}{{ checkbox }}{# other code #} {% endfor %} where form.categories is a multiple select field (no doubt this technique could be applied to radio buttons and a single select field). The filter does use some internal interfaces, but may well still work on newer Django version.

Read More

JSON fixtures of Intl. country codes & dial-codes

Just a dump of a countries data, including standard codes & dial-codes, based on the following model: - Country -- name : CharField -- code : CharField -- dial_code : CharField Note that countries aren't unique, as some may have several intl. dial codes. You can parse it using script or load it using the loaddata command.

  • json
  • fixtures
  • data
  • country
  • countries
  • codes
  • dial_codes
  • international
Read More

PostgreSQL fulltext with language translations

Consider following models: class Product(models.Model): code = modeld.CharField() class ProductTrans(models.Model): product = models.ForeignKey('Product') language = models.ChoiceField(choices=settings.LANGUAGES) title = models.ChaField() description = models.ChaField() With this snippet is possible search through all translations of product at the same time (using string concatenation in trigger): Product.objects.extra( where = ['product_product.fulltext @@ to_tsquery(%s)'], params = [ 'someproduct' ] ) For PostgreSQL >=8.4 only.

  • sql
  • models
  • translations
  • model
  • full-text
  • postgres
  • postgresql
  • language
  • fulltext
  • translation
Read More

mkrange - create a range() inside a template - variable/filter support for range values

Ok, I just took [wolever](http://djangosnippets.org/users/wolever/)'s snippet at [http://djangosnippets.org/snippets/1926/](http://djangosnippets.org/snippets/1926/) and added template variable/filter support for range values. For instance, you could write something like this: `{% mkrange 1 tool_page.paginator.num_pages|add:"1" as page_range %}` I'm just learning python and django, so any advice would be appreciated.

  • django
  • python
  • custom tag
Read More

RadioSelectWithHelpText

A Django form widget which displays help text for individual items in a set of radio buttons. It overrides the RadioSelect widget, adding a small bit of HTML after each <input> element, with the help text for each item. It was developed for a Django Dash project I'm working on (called transphorm.me), so isn't as feature-rich as it could be, but if you have any trouble installing it - or if I've miscopied any of my code in my rush - please let me know.

  • newforms
  • forms
  • widgets
  • radioselect
Read More

[UPDATE]Filter to resize a ImageField on demand + RATIO OPTION + CLEANUP

This is the snippet of rafacbd but upgraded... (http://djangosnippets.org/snippets/955/) Now support keep the aspect ratio or not, changing the size string (x1, x0) this choice use pil.resize or pil.thumbnail. Remember change the variable CAPS NAMES of the cleanup code. This cleanup function get the original main image file name and create a regexp similar to "[filename]_[width]x[height]x[ratio].[ext]" and remove all thumbs. By example if the main image is spain_rulez.jpg the script remove by example spain_rulez_100x100x1.jpg spain_rulez_200x150x0.jpg etc... etc...

  • template
  • image
  • thumbnail
  • cleanup
Read More

comments_allowed function for your model/...

Use this if you want to check if commenting is allowed for a certain object/model/... in a template. Like this; `{% if not object.comments_allowed %} <p>Comments are now closed.</p> {% else %} {% render_comment_form for object %} {% endif %}` You can replace the CommentModerator class with your own custom moderation class ofcourse.

  • comments
  • moderation
Read More

A ModelChoiceField with support for title in options based on a field in the model

ModelChoiceTitleField is a ModelChoiceField descendent that creates <OPTIONS> with title elements based on the field specified in title_source_field: priority=ModelChoiceTitleField(Priority.objects.all(), initial=Priority.objects.get(default=True).id, title_source_field='long_description') That will generate a `<SELECT>` element looking like: <select name="priority" id="id_priority"> <option value="1" title="Some extremely important task.">Emergency</option> ... </select> In the `<option>` above, the title was retrieved from the `long_description` field for the instance of the Priority class. The word Emergency came from a call to the instance of the Priority class' `__unicode__()` method. The value of the option is the PK for the instance of the Priority class.

  • ModelChoiceField
Read More

Return to a filtered changelist on change form save

You've filtered your changelist in your admin site and you want to edit a few entries here; you click on an object, edit it and press save, and you end up back at the default unfiltered changelist view. This ModelAdmin override is so that if you press "save" (not "save and add another", or "save and continue editing") you end up back at your filtered changelist. There are other ways out there and other snippets to do similar; however I hadn't seen one to only redirect if you pressed save so this is what I came up with. Hopefully it's useful.

  • admin
  • redirect
Read More

Easy configuration for relocatable sites

Deploying relocatable Django sites isn't currently as trivial as it should be (see http://code.djangoproject.com/ticket/8906, http://groups.google.com/group/django-developers/tree/browse_frm/thread/fa3661888716f940/). This snippet relocates all url patterns (similarly to http://djangosnippets.org/snippets/2129/) as well as the absolute url settings of `settings.py`. This allows deployment under a different mount point with a single Django setting, without having to repeat the mount point again as a SCRIPT_NAME parameter supplied by the web server.

  • deployment
  • mount point
  • relocatable
Read More

3109 snippets posted so far.