Login

Most bookmarked snippets

Snippet List

Non-pickling locmem (in-process memory) cache backend

You can use this cache backend to cache data in-process and avoid the overhead of pickling. Make absolutely sure you don't modify any data you've stored to or retrieved from the cache. Make deep copies instead if necessary. The backend is basically identical to Django's stock locmem cache (as of r15852 - after 1.3rc1) with pickling removed. It has been tested with that specific Django revision, so basically it's >=1.3 compatible. See [Django ticket #6124](http://code.djangoproject.com/ticket/6124) for some background information.

  • cache
  • pickle
  • backend
  • locmem
  • memory
  • process
Read More

Lorem ipsum -> Karel ende Elegast

Utility functions for generating dummy ("lorem ipsum") text, with text from the "Karel ende Elegast" old-Dutch epic poem. [wikipedia](http://en.wikipedia.org/wiki/Karel_ende_Elegast) by Wicher Minnaard <[email protected]> [website](http://smorgasbord.gavagai.nl/) Sort-of monkey-patches django.contrib.webdesign.lorem_ipsum (it's an experiment). Hopefully threadsafe, so both lorem_ipsum and elegast module functions can be accessed simultaneously.

  • mockup
  • lorem-ipsum
  • karel-ende-elegast
Read More

Make runfcgi fail when database connection is open before fork

FastCGI handler in prefork mode first imports every application, then forks. If any application during import opens connection to database, open connection is inherited by all of child processes; open db connection cannot be shared between processes, and if one process sends a request, another can receive a reply; also, if one process closes it, others have a desynchronized database handle. See: * http://stackoverflow.com/questions/1573579/psycopg2-disconnects-from-server * http://stackoverflow.com/questions/393637/django-fastcgi-randomly-raising-operationalerror * http://code.djangoproject.com/ticket/13215 * http://groups.google.com/group/django-users/browse_thread/thread/2c7421cdb9b99e48 If you put this snippet in your project-level __init__.py, then running manage.py runfcgi will fail loudly if the database connection is open in the parent process. This will happen only when you provide debug=true option to runfcgi to avoid monkey-patching code that runs in production mode.

  • fcgi
  • prefork
  • flup
Read More

Other approach of making middleware (by decorators)

Other approach of making middleware. Advantage of is to specify, which middleware is used for which view function and in what order. Middleware function gets all arguments, that are passed to view function. **Example usage** @RequestMiddleware def print_params_middleware(request, *args, **kwargs): print 'GET params:', request.GET @ResponseMiddleware def modify_headers_middleware(request, response, *args, **kwargs): response['Content-Type'] = 'text/html' @ExceptionMiddleware def catch_error_middleware(request, e, *args, **kwargs): return HttpResponse('catched error %s' % e ) @modify_headers_middleware @catch_error_middleware @print_params_middleware def some_view(request, *args, **kwargs): print 'someview' return HttpResponse()

  • middleware
  • decorator
  • exception
Read More

Better Django Model Field Choices

Nice to name your constant multiple choice fields in models, this is one way of doing that. Sorry I haven't looked into existing alternatives. But this approach worked for me.

  • choice
  • choices
  • model
  • field
Read More

Get default form data

Given an unbound form, determine what data would be generated from POSTing the form unchanged. The goal is to end up with a dict such that, passed into another form constructor as its data kwarg, form.changed_data == [].

  • forms
  • widgets
Read More

Bulk Insert Manager

This is a small manager that just adds a "bulk_insert" function. This is very basic, I'm basically throwing it up here because it's simple and works for my current needs. Feedback on improvements (which I know would be a ton) are very welcome. Some known "gotchas": 1. This doesn't handle relationships. If, however, you want to do one-to-one or foreignkeys you'll have to use the actual table column name ('whatever_id' typically) 2. When using this I typically make a bulk_insert call every 500 iterations or so Some improvements that I think could be good: 1. Possibly just find the fields from the first object in the objs array and leave the fields argument as optional 2. Create a bulk_insert_from_file function and use LOAD DATA INFILE for mysql and whatever else supports it

  • manager
  • bulk
  • insert
  • bulk-insert
Read More

Group sequence into rows and columns for a TABLE

Two template tag filters that can be used to create a table from a sequence. <table> {% for row in object_list|groupby_columns:3 %} <tr> {% for obj in row %} <td>{{ obj }}</td> {% endfor %} </tr> {% endfor %} </table> The example above would create a table where items read from top to bottom, left to right, in 3 columns. "Empty" cells are added to the sequence by the filter so that your rows balance.

  • filter
  • templatetag
  • table
  • groupby
Read More

Compact list_filter with counter

This is an extension of the fantastic snippet "Compact list_filter" written by **onlinehero**. Follow his instructions for the installation. My version add the number of filtered objects beside the label of the filters defined by the list_filter property.

  • admin-interface
  • compact
  • list_filter
Read More

Django Number Input

This will give you a <input type='number'> field. This is helpful when you want to use HTML5 for newer browsers. Older browsers will just interpret this as <input type='text'>

  • django
  • django-forms
  • input-types
Read More

Decoupling models with cross-database relations

The snippet enables decoupling model classes, associated with a ForeignKey, for the purpose of separating them into two databases. Looking at the following example: class Reporter(models.Model): ... class Article(models.Model): reporter = models.ForeignKey(Reporter) We want to separate the `Reporter` and `Article` into two separate databases, but this won't work in Django because of the [cross model relations](http://docs.djangoproject.com/en/dev/topics/db/multi-db/#cross-database-relations). The solution is to use an ID field and not a `ForeignKey` one. This makes the access very uncomfortable. The above class will make this a bit less awkward. It doesn't support the [RelatedManager](http://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager), but it will support accessing the related field as you normally would. The article class will look like this (assuming the reporter model id field is an `IntegerField`): class Article(DecoupledModel): reporter_id = models.IntegerField() _linked_fields = { 'reporter': Reporter, } Once you have an article object, you can access the reporter as you normally would for both read and writing. For example: my_reporter = article1.reporter article2.reporter = my_reporter

  • django
  • model
  • database
Read More

Latest tweets Templatetag

Based on [http://djangosnippets.org/snippets/1615/](http://djangosnippets.org/snippets/1615/) Added tweets cache. Cache time is configurable through project settings: TWITTER_TIMEOUT=300. Default time is 300 seconds = 5 minutes. This improve performance by reducing the twitter api queries interval.

  • templatetag
  • twitter
  • social
Read More

3110 snippets posted so far.