Login

All snippets written in Python

Snippet List

Reset cache between tests

I don't understand why the cache is accumulated between the tests. I thought one of the axioms of unit testing is that the tests should not affect each other. Couldn't find anything that explains why it's done this way but it seems a bit strange. Anybody know if there's a reason or is this a reason for me to upload a patch to Django code?

  • cache
  • tests
  • locmem
  • setup
Read More

Ajax auto-filtered Foreign Key Field

Say you have a ModelChoiceField and you want the choices to depend on the value of another field in the form... that's what these bits are for. They need to be used in conjunction with the Ajax views from: [code.google.com/p/django-ajax-filtered-fields/](http://code.google.com/p/django-ajax-filtered-fields/) See my blog for full details: [anentropic.wordpress.com](http://anentropic.wordpress.com) ...um, this is work in progress and the explanatory blog post is not up yet...

  • ajax
  • widget
Read More

Stacked/Grouped Forms 2 - easy rendering forms

This snippet was inspired by [1783](http://www.djangosnippets.org/snippets/1783/). It allows simply create groups of fields for template rendering.

  • template
  • fields
  • forms
  • templates
  • fieldset
  • form
  • object
  • field
  • fieldsets
  • groups
  • stacked
  • descriptor
Read More

Google Closure support in django-compress

A filter to integrate Google Closure compiler in django-compress plugin. 1. [download django-compress](http://code.google.com/p/django-compress/) 2. install it 3. [download Closure Compiler](http://code.google.com/closure/compiler) 4. put the jar at the root of your project 5. put this snippet as a **__init__.py** file in a **google_closure** directory in the filters directory of the plugin 6. add `COMPRESS_JS_FILTERS = ('compress.filters.google_closure.GoogleClosureCompilerFilter',)` to your settings.py You can test `COMPRESS_CLOSURE_JS_ARGUMENTS = {'compilation_level': 'ADVANCED_OPTIMIZATIONS', }` in your settings.py too

  • google
  • js
  • minify
  • closure
  • compress
Read More

decorator for method attribute assignment

A bit cleaner syntax for method attribute assignment; used in models for 'short_description'. >from mysite.polls.models import Poll >poll = Poll.objects.get(pk=1) >poll.was_published_today.short_description >>>'Published today?'

  • models
  • decorator
Read More

Stacked/Grouped Forms

This snippet provides support to create a bit more advanced forms, eg group fields together vertically and horizontally. It's a bit similar to the options one has about displaying fields in the admin.

  • forms
  • groups
  • stacked
Read More

Fix for GZipMiddleware when serving files or streaming or using iterators

A simple replacement for Django's default GZipMiddleware which breaks when trying to serve files or pass any kind of iterators to the HttpResponse object. Simply replace GZipMiddleware with the provided middleware and set response.dontgzip = True when returning the response, and it will then be ignored by the middleware.

  • files
  • gzip
  • streaming
  • gzipmiddleware
Read More

django-mptt enabled FilteredSelectMultiple m2m widget

If you are using django-mptt to manage content (eg heirarchical categories) then it needs a bit of help to make a nice admin interface. For many-to-many fields, Django provides the quite nice FilteredSelectMultiple widget (a two-pane selection list with search box) but it only renders 'flat' lists... if you have a big category tree it's going to be confusing to know what belongs to what. Also, list items are sorted alphabetically in the js, which won't be what you want. This snippet extends FilteredSelectMultiple to show the tree structure in the list. You'll also need the js from this snippet: [#1780](http://www.djangosnippets.org/snippets/1780/) For usage details see my blog at: [http://anentropic.wordpress.com](http://anentropic.wordpress.com/2009/11/05/more-django-mptt-goodness-filteredselectmultiple-m2m-widget/)

  • widget
  • mptt
Read More

pyText2Pdf - Python script to convert plain text into PDF file. Modified to work with streams.

This is "pyText2Pdf" - Python script to convert plain text into PDF file. Originally written by Anand B Pillai. It is taken from http://code.activestate.com/recipes/189858/ Modified to work with streams. Example: produce PDF document from text and output it as HTTPResponse object. import StringIO input_stream = StringIO.StringIO(text) result = StringIO.StringIO() pdfclass = pyText2Pdf(input_stream, result, "PDF title") pdfclass.Convert() response = HttpResponse(result.getvalue(), mimetype="application/pdf") response['Content-Disposition'] = 'attachment; filename=pdf_report.pdf' return response

  • django
  • tools
  • python
  • pdf
  • converter
  • text2pdf
  • adobe
  • acrobat
  • processing
Read More

Use git log to give your app a revision

Put that stuff in your settings.py Then you can use the git log last date to make that your "revision number" assuming you don't use regular version release numbers. With it you can do something like: <div id="footer"> &copy; My Company &mdash; The Super App (revision {{ GIT_REVISION_DATE }}) </div> See if you like it

  • settings
  • subprocess
  • git
Read More

MPTTModelAdmin

This builds on a couple of other people's hacks to effectively manage django-mptt models via the admin. One problem you find is if you use the actions drop-down menu to ‘delete selected’ items from your mptt model… the bulk actions bypass the model’s delete method so your left/right values for the tree aren’t updated. What you need is a way to automatically rebuild the tree after a bulk action. This code provides that facility. Full details on my blog: [http://anentropic.wordpress.com/2009/10/26/](http://anentropic.wordpress.com/2009/10/26/making-admin-bulk-delete-action-work-with-django-mptt/)

  • admin
  • mptt
Read More

Middleware: Record ownership screener

UPDATE: 'ORDER BY' in de regex is now optional If enabled while coding just keep track of your console output for: <<< WARNING >>> Query execution without ownership clause, called from "process_response" Happy coding Regards, Gerard.

  • middleware
  • user
  • permission
  • ownership
  • created_by
Read More

Improved generic foreign key manager 2

This is an improvement on [snippet 1079](http://www.djangosnippets.org/snippets/1079/). Please read its description and [this blog post](http://zerokspot.com/weblog/2008/08/13/genericforeignkeys-with-less-queries/) for any information. This is a manager for handling generic foreign key. Generic foreign objects of the same type are fetched together in order to reduce the number of SQL queries. To use, just assign an instance of GFKManager as the objects attribute of a model that has generic foreign keys. Then: `MyModelWithGFKs.objects.filter(...).fetch_generic_relations()` The generic related items will be bulk-fetched to minimize the number of queries. **Improvement:** Problem I had with previous version from snippet 1079 : if two or more items shares the same generic foreign object, then only the first one is cached. Next ones generates new unwanted SQL queries. I solved this problem by putting all the needed foreign objects in a temporary data_map dictionary. Then, the objects are distributed to every items, so that if two items shares the same foreign object, it will only be fetched once.

  • foreignkey
  • generic
  • manager
  • query
  • tuning
Read More

Strip Google Analytics cookies for caching middleware purposes

You may notice that using Google Analytics's 'urchin' with the CacheMiddleware and SessionMiddleware or AuthenticationMiddleware middleware classes means that nothing is ever cached. Google Analytics updates its cookies with every page view, and the Auth/Session middlewares add cookies to the caching engine's 'Vary' list. This means every page view is given a unique cache key. This middleware class will remove urchin's '__utmX' cookies from the request object before it hits the caching middleware. Put it at the top of your MIDDLEWARE_CLASSES in settings.py. nf / [email protected]

  • middleware
  • cache
  • google
  • analytics
Read More
Author: nf
  • 7
  • 13

hide emails with PIL - template filter

This template filter converts email text to image with the email text. It uses PIL and it makes the image as high and wide as the text. This template filter is intended to be used as **anti-spider** protection.

  • email
  • mailhide
Read More

2956 snippets posted so far.