Login

All snippets written in Python

Snippet List

Generic object_detail view with multiple named URL filters

This snippet is greatly inspired by [@jlorich](http://djangosnippets.org/users/jlorich/)'s useful [#2436](http://djangosnippets.org/snippets/2436/). The main difference is that I wanted to choose the names of my URL params instead of being forced into naming them "value1", "value2", etc. When reversing the URL you have to remember that the kwargs aren't friendly. By using the same names in the `filters` list, you don't have to change the way your otherwise write the URL pattern. Also it's clear throughout how you'll be filtering the QuerySet. The other change I made was "erroring early". This avoids running the QuerySet all over again inside `object_detail()` just to have it raise an exception we could have caught the first time.

  • filter
  • urlconf
  • generic-views
  • queryset
  • urlpatterns
Read More

TemplateZipFile

TemplateZipFile is a class for creating ZipFiles out of Django templates. Usage example: from zipfile import ZIP_DEFLATED from django_zipfile import TemplateZipFile def myview(request, object_id): obj = get_object_or_404(MyModel, pk=object_id) context = { 'object': obj } response = HttpResponse(mimetype='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=myfile.zip' container = TemplateZipFile(response, mode='w', compression=ZIP_DEFLATED, template_root='myapp/myzipskeleton/') container.add_template('mimetype') container.add_template('META-INF/container.xml') container.add_template('chapter1.html', context=context) container.close() return response

  • template
  • zipfile
Read More

another request logging middleware with request time and extra info

Simple logging middleware that captures the following: * remote address (whether proxied or direct) * if authenticated, then user email address * request method (GET/POST etc) * request full path * response status code (200, 404 etc) * content length * request process time * If DEBUG=True, also logs SQL query information - number of queries and how long they took

  • middleware
  • request-path
  • time
  • request
  • logging
  • time-logging
Read More

ModelChoiceField with option groups

This is a ModelChoiceField where the choices are rendered in optiongroups (this is already posible with a normal Choicefield) For this to work properly the queryset you supply should already be ordered the way you want (i.e. by the group_by_field first, then any sub-ordering)

  • modelchoicefield
Read More

create or update, then get, model instances from JSON/py dict

Basically the idea is to import/update model instances from a json data that closely matches the model structure (i.e. identical field names) From my answer to this question: [http://stackoverflow.com/a/8377382/202168](http://stackoverflow.com/a/8377382/202168) See the original question for sample data format.

  • json
  • import
Read More

Django Incremental Counter Tag

Counter tag. Can be used to output and increment a counter. For usage, see docstring in the code. This is the first complete tag that I've implemented, I hope that there are no bugs and that it's thread safe.

  • incremental
  • counter
  • increment
  • numbering
Read More

Active link

I needed a way to find if a menu items should be active. After searching the internet i found a few options*, but none of them did fit my needs, so i wrote my own: Usage: <a href="{% url 'view-name' %}" class="{% current request 'view-name' %}"></a> * http://gnuvince.wordpress.com/2008/03/19/the-new-and-improved-active-tag/ * http://stackoverflow.com/questions/340888/navigation-in-django

  • template
  • path
  • active
  • link
  • current
Read More

decorator for decorators with optional args

Have you ever wanted a decorator that you could apply either straight-out: @mydec def myfun(...): ... or with special arguments: @mydec(special=foo) def myfun(...): ... ? Well, decorate it with this metadecorator, and voila. (I had this idea independently, but it's been done before as decorator_withargs: http://osdir.com/ml/python.ideas/2008-01/msg00048.html. My version is actually useful because it deals with signatures and calling directly.) As http://www.siafoo.net/article/68 points out, the standard decorator module has too much magic: the "@decorator" decorator expects a wrapping function, not a working decorator. This module fixes that.

  • decorator
  • decoratordecorator
  • metadecorator
Read More

Cached model property decorator (like @property)

This is a nice decorator for using the cache to save the results of expensive-to-calculate but static-per-instance model properties. There is also a decorator for when the property value is another model, and the contents of the other model should not be cached across requests. 3 levels of caching implemented: * outermost: django cache * middle: obj._cache (for multiple properties on a single object) * innermost: replace the attribute on this object, so we can entirely avoid running this function a second time.

  • property
  • cache
  • decorator
Read More

2956 snippets posted so far.