Login

Most bookmarked snippets

Snippet List

format_thousands

Template filter to format a number so that it's thousands are separated by commas. {{ number|format_thousands }}

  • format
  • string
  • comma
  • decimal
  • number
  • thousands
  • float
Read More

Add GET parameters from current request

The tag generates a parameter string in form '?param1=val1&param2=val2'. The parameter list is generated by taking all parameters from current request.GET and optionally overriding them by providing parameters to the tag. This is a cleaned up version of http://djangosnippets.org/snippets/2105/. It solves a couple of issues, namely: * parameters are optional * parameters can have values from request, e.g. request.GET.foo * native parsing methods are used for better compatibility and readability * shorter tag name Usage: place this code in your appdir/templatetags/add_get_parameter.py In template: {% load add_get_parameter %} <a href="{% add_get param1='const' param2=variable_in_context %}"> Link with modified params </a> It's required that you have 'django.core.context_processors.request' in TEMPLATE_CONTEXT_PROCESSORS

  • get
  • request
  • parameters
  • add
Read More

Generic Autodiscovery

Admin-like autodiscover for your apps. I have copy/pasted this code too many times...Dynamically autodiscover a particular module_name in a django project's INSTALLED_APPS directories, a-la django admin's autodiscover() method.

  • autodiscover
Read More

Memento

This class tracks changes in Django Admin. When a save action is performed, it stores the value of the old object using the Memento model. Example of code for a model in **admin.py** for a custom 'app': from app.memento.models import Memento def save_model(self, request, obj, form, change): obj.save() data = serializers.serialize("json", [obj, ]) m = Memento(app="Unidade",model=modelName,data=data, user=request.user) m.save() class UnidadeAdmin(admin.ModelAdmin): pass UnidadeAdmin.save_model = save_model This stores the former values of 'Unidade' model on 'Memento' model data. Not tested on previous versions of Django, but could work on them too.

  • admin
  • register
  • changes
  • persistence
  • tracking
Read More

JsonObjectField

This fields.py file defines a new model field type, "JsonObjectField," which is designed to allow the storage of arbitrary Python objects in Django TextFields. It is intended primarily to allow the storage of Python dictionaries or list objects. As the name implies, it converts objects to JSON for storage; this conversion happens transparently, so from your model's perspective, the field stores and retrieves the actual objects.

  • model
  • json
  • database
  • object
Read More

utf8-friendly dumpdata management command (no escape symbols)

Adds `--pretty` option to django `./manage.py dumpdata` command, which produces pretty utf8 strings instead of ugly unicode-escaped shit: $ ./manage.py dumpdata app.pricingplan --indent=1 [ { "pk": 1, "model": "app.pricingplan", "fields": { "name": "\u0411\u0430\u0437\u043e\u0432\u044b\u0439", } }, { "pk": 2, "model": "app.pricingplan", "fields": { "name": "\u0425\u0443\u044f\u0437\u043e\u0432\u044b\u0439", } } ]% ./manage.py dumpdata app.pricingplan --indent=1 --pretty [ { "pk": 1, "model": "app.pricingplan", "fields": { "name": "Базовый", } }, { "pk": 2, "model": "app.pricingplan", "fields": { "name": "Хуязовый", } } ]%

  • fixtures
  • management
  • dumpdata
Read More

Add CSS class template filter

Sometimes you want to add CSS classes to HTML elements that are generated by Django using their `__unicode__` representation, eg. you can output a form field with `{{ form.name }}`, but if you would like to add a certain CSS class to the outputted input or select tag you would have to assort to plain HTML. Using this filter you can simply do something like `{{ form.name|add_class:"span-4" }}` which will render an input like `<input type="..." name="..." class="span-4`.

  • django
  • template tag
  • css class
  • template filter
Read More

Detailed Error Reporting by Email

The default traceback sent by email when an error occurs, usually gives too little information comparing it to the error page in the DEBUG mode. This snippet guerilla-patches error handling and sends by email the same information as you would see in DEBUG mode. To set it up, add the snippet to any `models.py` of an installed app. (I wonder why this hasn't been implemented in the core)

  • email
  • error
  • reporting
Read More

Simple Mobile Support

For those interested in making a mobile site geared toward the higher end devices, and wanting a little leverage over device-specific quirks. These are the big players in the U.S. market, but of course, add your own User-Agents to match your audience's popular browsers. Usage: <html class="{{ device.classes }}"> You can also leverage template logic: {% if device.iphone %} <p>You are browsing on {% if device.iphone = "iphone4" %} iPhone 4 {% else %} an iPhone pre-version 4{% endif %} </p> {% endif %}

  • mobile
  • context_processors
Read More

Polymorphic inheritance ala SQLAlchemy

This is a different take on polymorphic inheritance, inspired by SQLAlchemy's approach to the problem. The common Django approach (e.g. snippets 1031 & 1034, [django_polymorphic](http://github.com/bconstantin/django_polymorphic)) is to use a foreign key to `ContentType` on the parent model and override `save()` to set the right content type automatically. That works fine but it might not always be possible or desirable, for example if there is another field that determines the "real type" of an instance. In contrast this snippet (which is actually posted and maintained at [gist.github](http://gist.github.com/608595)) allows the user to explicitly specify the field that determines the real type of an instance. The basic idea and the terminology (`polymorphic_on` field, `polymorphic_identity` value) are taken from [SQLAlchemy](http://www.sqlalchemy.org/docs/orm/inheritance.html). Some other features: * It works for proxy child models too, with almost no overhead compared to non-polymorphic managers (since there's no need to hit another DB table as for multi-table inheritance). * It does not override the default (or any other) model Manager. Regular (non-polymorphic) managers and querysets are still available if desired. * It does not require extending a custom Model base class, using a custom metaclass, monkeypatching the models or any kind of magic.

  • inheritance
  • polymorphic
Read More

ResizeImageField

ResizeImageField ================ (extension of RemovableImageField) ================================= by Wim Feijen, Go2People. What does it do? ---------------- ResizeImageField is a replacement for django's ImageField. It has two major benefits: 1. Creation of thumbnails and scaled images. 1. Extends the image upload form and adds a preview and a checkbox to remove the existing image. It's easy to use: - Replace ImageField by ResizeImageField - No further changes are necessary Requirements: ------------- Working installation of PIL, the Python Imaging Library Usage ----- - add resize_image to your app - add resize_filters.py to your templatetags - in settings.py, set a PHOTO_DIR, f.e. photos/original - in models.py, add: - from settings import PHOTO_DIR - from resize_image import ResizeImageField - photo = ResizeImageField(upload_to=PHOTO_DIR, blank=True) Scaled images will be stored in 'photos/scaled', thumbnails will be stored in 'photos/thumb'. Access your images from your template. Add:: {% load resize_filters %} {{ address.photo.url|thumb }} or:: {{ address.photo.url|scaled }} Defaults ------- - Scaled images are max. 200x200 pixels by default - Thumbnails are 50x50 pixels. Override the default behaviour in settings.py Scaling is done by PIL's thumbnail function, transparency is conserved. Credits ------ This code is an adaptation from python snippet 636 by tomZ: "Updated Filefield / ImageField with a delete checkbox"

  • image
  • thumbnail
  • resize
  • scale
  • delete
  • ImageField
  • ResizeImageField
  • removable
Read More
Author: wim
  • 5
  • 5

3110 snippets posted so far.