Login

Snippets by miracle2k

Snippet List

UTC-based astimezone filter

A version of http://djangosnippets.org/snippets/2388/ which assumes UTC-based dates. This is when you store dates in UTC (as you should), and want to display them in your site's local timezone, and you notice that Django's timesince/time template tags still do not support timezones.

  • timezone
  • utc
  • timezones
  • times
Read More

Template loader to target a specific template

This is http://djangosnippets.org/snippets/1376/ rewritten as a new class-style Loader, and slightly improved. Allows you to reference templates like this: app_label:some/template/name.html This makes it possible to insert customizations at any point in a template hierarchy. For example, you could replace a block within the base admin template: {% extends "admin:admin/base.html" %} {% block breadcrumbs %}Custom Breadcrumbs-Style{% endblock %}

  • templates
  • loader
Read More

Copy a model instance

Create a copy of a model instance. Works in model inheritance case where ``instance.pk = None`` is not good enough, since the subclass instance refers to the parent_link's primary key during save. M2M relationships are currently not handled, i.e. they are not copied. See also Django #4027.

  • model
  • copy
Read More

Digg-like paginator, updated

This is an updated version of http://www.djangosnippets.org/snippets/628/ now working with Django's new Paginator class, instead of the deprecated ObjectPaginator. See: http://blog.elsdoerfer.name/2008/05/26/diggpaginator-update/

  • pagination
  • paginator
  • digg
Read More

Passing values to a method from a template

A simple trick to let a function be called with exactly ONE argument from a Django template, by passing it via an attribute. Example: class SearchResult(object): @template_callable def highlighted(self, field): return self._xappy_result.highlight(field) result = SearchResult() result.highlighted.title {{ result.highlighted.title }}

  • template
  • templates
  • method
  • call
  • arguments
Read More

Stateful paginator, digg style

**This code will throw deprecation warnings in newer Django checkouts - see the http://www.djangosnippets.org/snippets/773/ for an improved version that should work with the recent trunk.** objects = MyModel.objects.all() paginator = DiggPaginator(objects, 10, body=6, padding=2, page=7) return render_to_response('template.html', {'paginator': paginator} {% if paginator.has_next %}{# pagelink paginator.next #}{% endif %} {% for page in paginator.page_range %} {% if not page %} ... {% else %}{# pagelink page #} {% endif %} {% endfor %} http://blog.elsdoerfer.name/2008/03/06/yet-another-paginator-digg-style/

  • pagination
  • paginator
  • digg
Read More

Decorating urlpatterns

One thing I wanted for a while was the ability to basically apply something like @login_required to a bunch of urlpatterns in one go, instead of having to decorate each and every view manually. In this example, the latter two views will always raise a 404.

  • urls
  • views
  • decorators
  • urlpatterns
Read More

Template tag: Extend with parameters

Extended extends tag that supports passing parameters, which will be made available in the context of the extended template (and all the way up the hierarchy). It wraps around the orginal extends tag, to avoid code duplication, and to not miss out on possible future django enhancements. Note: The current implementation will override variables passed from your view, too, so be careful. Some of the argument parsing code is based on: http://www.djangosnippets.org/snippets/11/ Examples: {% xextends "some.html" %} {% xextends "some.html" with title="title1" %} {% xextends "some.html" with title="title2"|capfirst %}

  • template
  • templatetag
  • extends
  • parameters
Read More

Automatically trim newforms text fields

Makes sure the value a user entered into a a text-based field is automatically trimmed during form cleaning / validation. The 'field' parameter is expected to be a newforms.fields.Field _instance_.Only modifies str and unicode descending values, and passes everything else on untouched. Example: form = form_for_model(Person) make_trimming(form.fields['name'])

  • newforms
  • strings
  • trim
Read More

filter/search a newforms select widget

Adds a filter input above a select widget that allows live-filtering on the client-side (no ajax) in Firefox. Example: make_fields_searchable(ModelItemForm, { 'publisher': {'set_size': 8}, 'developer': {'set_size': 8}, 'genre': {}, 'platform': {} })

  • filter
  • newforms
  • search
  • model
  • widgets
  • select
Read More

Yet another SQL debugging facility

Inspired by http://www.djangosnippets.org/snippets/159/ This context processor provides a new variable {{ sqldebug }}, which can be used as follows: {% if sqldebug %}...{% endif %} {% if sqldebug.enabled %}...{% endif %} This checks settings.SQL_DEBUG and settings.DEBUG. Both need to be True, otherwise the above will evaluate to False and sql debugging is considered to be disabled. {{ sqldebug }} This prints basic information like total number of queries and total time. {{ sqldebug.time }}, {{ sqldebug.queries.count }} Both pieces of data can be accessed manually as well. {{ sqldebug.queries }} Lists all queries as LI elements. {% for q in sqldebug.queries %} <li>{{ q.time }}: {{ q }}</li> {% endfor %} Queries can be iterated as well. The query is automatically escaped and contains <wbr> tags to improve display of long queries. You can use {{ q.sql }} to access the unmodified, raw query string. Here's a more complex example. It the snippet from: http://www.djangosnippets.org/snippets/93/ adjusted for this context processor. {% if sqldebug %} <div id="debug"> <p> {{ sqldebug.queries.count }} Quer{{ sqldebug.queries|pluralize:"y,ies" }}, {{ sqldebug.time }} seconds {% ifnotequal sql_queries|length 0 %} (<span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.display=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</span>) {% endifnotequal %} </p> <table id="debugQueryTable" style="display: none;"> <col width="1"></col> <col></col> <col width="1"></col> <thead> <tr> <th scope="col">#</th> <th scope="col">SQL</th> <th scope="col">Time</th> </tr> </thead> <tbody> {% for query in sqldebug.queries %}<tr class="{% cycle odd,even %}"> <td>{{ forloop.counter }}</td> <td>{{ query }}</td> <td>{{ query.time }}</td> </tr>{% endfor %} </tbody> </table> </div> {% endif %}

  • sql
  • debug
  • queries
  • db
  • database
  • contextprocessor
Read More

Repeat blocks with new context / simple Jinja-like macro system

A simple macro system that makes it possible to reuse previously defined blocks, optionally with a custom context, similar to the macro functionality in Jinja. It requires some workarounds/hacks because we cannot reach all the data from inside the django template system that we need, but it seems to work pretty well so far. It is, however, also pretty untested at this point, so use at your own risk. Examples: base.html: <!-- This is mandatory if you want to use the repeat-tag in a template. It should as placed as earily as possible. See below for how to mix with template inheritance. --> {% enablemacros %} <!-- Note that {{ param }} does not exist. --> {% block foo %} A standard django block that will be written to the output. {% if param %}{{ param }}{% endif %} {% endblock %} {% macro bar %} Pretty much the same thing as a django block (can even be overridden via template inheritance), but it's content will NOT be rendered per default. Please note that it ends with ENDBLOCK! {% if param %}{{ param }}{% endif %} {% endblock %} <!-- Render foo for the second time --> {% repeat foo %} <!-- Render foo bar the first time --> {% repeat bar %} <!-- Render both blocks again, and pass a parameter --> {% repeat foo with "Hello World" as param %} {% repeat bar with "Hello World" as param %} {% macro form %}do stuff with: {{ form }}{% endblock %} {% for form in all_forms %} {% repeat display %} <!-- will have access to {{ form }} {% endfor %} extend.html: <!-- {% extends %} requires that it be the first thing in a template, and if it is, everything except for block tags is ignored, so {% enablemacros %} won't work. Instead, use: --> {% extends_with_macros 'base.html' %} {% block foo %} Will override "foo" in base.html {% endblock %} {% block bar %} Will override the macro block "bar" in base.html. Whether this is defined as block or macro doesn't matter. {% endblock %} Todo: * This (both tags used) results in infinite recursion: {% extends_with_macros "somefile" %}{% enablemacros %}

  • templates
  • macro
  • jinja
  • repeat
  • reuse
  • variables
Read More

Load templatetag libraries via settings

In your settings file: TEMPLATE_TAGS = ( "djutils.templatetags.sqldebug", ) Make sure load_templatetags() gets called somewhere, for example in your apps __init__.py *Edit: Updated to work with templatetag libraries that use certain critical django-bits.*

  • templates
  • settings
  • tags
  • templatetags
  • conf
Read More

Validation for 'unique' and 'unique_together' constraints (different version)

This is a slightly different and extendend version of this snippet: http://www.djangosnippets.org/snippets/260/ Unique constraints for single fields are validated in a clean_FIELD, instead of globally in the form's clean() method, so that the error messages are correctly assigned to each field. Additionally, you can specify mappings for unique_together constraints to assign those error messages to a specific field as well (instead of having them in non_field_errors(), where they would normally be.

  • newforms
  • forms
  • validation
  • unique_together
  • unique
  • constraints
Read More

miracle2k has posted 22 snippets.