Login

Top-rated snippets

Snippet List

Initially open collapsable fieldset class in admin

It's just an extension for the admin. Replace the collapse.js (collapse.min.js) and use it like this in the admin fieldset option: ´´**'classes': ['collapse', 'open']**´´. Without the 'open'-class, it will work as usual. *Needs possibly fixing for IE <= 8* because IE doesn't support the ´´:not´´ selector.

  • fieldset
  • collapse
  • collapsed
  • open
  • show
Read More

Improved many-page pagination

This one was adapted from [Page numbers with ... like in Digg](http://djangosnippets.org/snippets/1441/). See that one for more reference. Digg-like page numbering using inclusion tag. Usage in template: `{% load pagination %} {% pagination yourpage %}` Inclusion template pagination.html: {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}"><img src="{{ MEDIA_URL }}images/page/cyclenav_l.png" alt="Previous page" /></a> {% endif %} {% for pnum in begin %} <a href="?page={{ pnum }}"{% if page.number == pnum %} class="active"{% endif %}>{{ pnum }}</a> {% endfor %} {% if middle %} <strong>...</strong> {% for pnum in middle %} <a href="?page={{ pnum }}"{% if page.number == pnum %} class="active"{% endif %}>{{ pnum }}</a> {% endfor %} {% endif %} {% if end %} <strong>...</strong> {% for pnum in end %} <a href="?page={{ pnum }}"{% if page.number == pnum %} class="active"{% endif %}>{{ pnum }}</a> {% endfor %} {% endif %} {% if page.has_next %} <a href="?page={{ page.next_page_number }}"><img src="{{ MEDIA_URL }}images/page/cyclenav_l.png" alt="Previous page" /></a> {% endif %}` Produces: previous_img 1 2 ... 4 5 6 7 8 9 10 11 12 ... 17 18 next_img Or: 1 2 3 4 5 6 7 8 ... 17 18 next_img Or: previous_img 1 2 ... 10 11 12 13 14 15 16 17 18 next_img

  • tag
  • django
  • templatetag
  • pagination
  • digg
  • pages
Read More

ReportBug() (exception emails - ala django debug style)

ReportBug() allows you to send exception details to you, via email, but with far more detail than the default. It uses the base function for the traceback used by the Debug mode on Django. This is a first revision, so the emails have no decent styling, but it works, and shows scope on each stack. It will automatically generate a random serial number per error, so you can track them in your favourite bug tracker. It also has support for you to pass it a request variable, so the mail would also contain request/response context. Again, i'm gonna look into doing this manually in the future. Hope this helps! Mwah. Cal Leeming. cal [at] simplicitymedialtd.co.uk. Simplicity Media Ltd.

  • email
  • debug
  • mail
  • exception
  • report
  • bug
  • mail_admins
  • reportbug
Read More

ModelValue for djagno-livesettings

Extension for django-livesettings project - http://bitbucket.org/bkroeze/django-livesettings/ Allow to specify the model instance in settings Usage: config_register( ModelValue(BASE_GROUP, 'TestValue', queryset = Value.objects.all(), required=False)

  • livesettings
Read More

Parse custom template tag's args or kwargs

Enhanced version of snippet [1113](http://djangosnippets.org/snippets/1113/) Usage example (not self-contained): @register.tag def groupurl(parser, token): ''' Syntax:: {% groupurl view_name group [key=val, [key=val, ...]] [as varname] %} Example:: <a href="{% groupurl blog_detail group slug=blog.slug %}">{{ blog.name }}</a> ''' bits = token.contents.split() tag_name = bits[0] if len(bits) < 3: raise template.TemplateSyntaxError("'%s' takes tag at least 2 arguments (path to a view and a group)" % (tag_name,) bits_iter = iter(bits[1:]) # view_name + group and url kwargs args, kwargs = parse_args_and_kwargs(parser, bits_iter, stop_test='as', tagname=tag_name) if len(args) != 2: raise template.TemplateSyntaxError("'%s' takes exactly two non-kwargs (path to a view and a group)" % (tag_name,)) view_name, group = args # as var asvar = None for bit in bits_iter: asvar = bit return GroupURLNode(view_name, group, kwargs, asvar)

  • tag
  • templatetag
  • parse
  • args
  • kwargs
Read More

One step up from __icontains

The [REGEX and IREGEX](http://docs.djangoproject.com/en/dev/ref/models/querysets/#iregex) operators were added in Django 1.0 and I'm sure you can think of fancier ways of doing word delimiting and things like that but this was all I needed to make a user-friendly autocomplete search function.

  • ORM
  • QuerySet
Read More

Checkbox or radio iterator as template filter

This snippet is based on [Bill Freeman's MultiSelect checkbox iterator template filter](http://djangosnippets.org/snippets/2151/). Usage: See docstring

  • checkbox
  • choice
  • templatefilter
  • iterator
  • checkbox-input
  • form-choice
  • radio-button
  • radio-input
Read More

change settings locally in an individual test

So you need to change some settings when running an individual test in a test case. You could just wrap the test between `old_value = settings.MY_SETTING` and `settings.MY_SETTING = old_value`. This snippet provides a helper which makes this a bit more convenient, since settings are restored to their old values automatically. Example usage: class MyTestCase(TestCase): def test_something(self): with patch_settings(MY_SETTING='my value', OTHER_SETTING='other value'): do_my_test()

  • settings
  • testing
  • unittest
Read More

Encode emails as URIs

Put this snippet in a file in a templatetags/ directory and load it in your templates. Then use it to encode your emails: `{{"[email protected]"|html_encode_email}}` Or if you want some control over the anchor tag: `<a href="mailto:{{"[email protected]"|html_encode}}&subject=Feedback">Send Feedback</a>` From [fahhem.com](http://fahhem.com/) and [Recrec Labs](http://recreclabs.com/)

  • templatetag
  • email
  • spam
  • encode
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

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

adding fields to User model

This code adds new field to Django user model. It must be executed early as much as possible, so put this code to __init__.py of some application.

  • fields
  • model
  • user
  • auth
  • field
Read More

Filter to generate QR codes

You can convert any string to a QR code image as easy as use a simple filter, thanks to google charts api. Common use: <img src="{{object.attribute_to_encode|qr:"120x130"}}" /> This will create a 120(width) x 130(heiht) image with the value of the attribute_to_encode encoded in a QR coded image.

  • filter
  • templatetag
  • templatefilter
  • barcode
  • qr
Read More

Interactive Profiling Middleware

Based on [Extended Profiling Middleware](http://djangosnippets.org/snippets/605/), this version allows interactive sorting of functions and inspection of SQL queries.

  • middleware
  • profile
  • hotshot
Read More

3110 snippets posted so far.