Login

3110 snippets

Snippet List

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

@url decorator improvements

A slight modification (and, I think, improvement) of the URL decorator found in [snippet 395](http://www.djangosnippets.org/snippets/395/). What's different between this snippet and 395? 1. We use `django.conf.urls.defaults.url()` when adding patterns 2. We support arbitrary arguments to the `url()` method (like `name="foo"`) 3. We _do not_ support multiple url patterns (this didn't seem useful to me, but if it is I can add it back.)

  • urls
  • url
  • decorator
  • decorators
  • urlpatterns
Read More

Use both NTLM and Anonymous authentication with IIS

Point '^accounts/login/$' or whatever your custom login path is to the 'negotiate_ntlm' view. This allows you to keep anonymous authentication enabled on IIS and easily lock down just the parts of the site you need to (e.g. [admin](http://djangosnippets.org/snippets/2127/)).

  • admin
  • authentication
  • anonymous
  • iis
  • ntlm
Read More

Django 1.2+ template loader for Jinja2

This is a minimal template loader for Django 1.2 or higher that loads [Jinja2](http://jinja.pocoo.org/2/) templates. It is better integrated with Django than using Jinja2 directly: * Your view code is the same * Unmodified generic views use it * RequestContext and context processors still work To use it, add the following to you `settings.py` file: TEMPLATE_LOADERS = ( 'jinja2_for_django.Loader', ) It searches for templates in the same places as `django.template.loaders.app_directories.Loader` − that is in the `templates` directory of each installed app. Django custom and default template tags and filters are not available. Some are the same in Jinja2, but you need to replace the others yourself. You can add global filters and variables (such as functions) in the `Loader.env.filters` and `Loader.env.globals` dicts. You can not add tags. See the [Jinja2 documentation](http://jinja.pocoo.org/2/documentation/) for more details.

  • template
  • jinja
  • jinja2
  • django1.2
Read More

load m2m fields objects

I have a ModelForm which includes m2m field to images. User can upload images and crop them with my cool jquery cropper, then areas are saved as images and their IDs and thumbnail URLs are passed back to page and included as thumbnails with hidden inputs. I have no problem while form have no errors, and when it does, i can not just simply display thumbnails — all I have is IDs, and form has no objects to iterate cause instance was not saved, and as it was not save it has no id and as it has no id it can not have m2m relations. So i wrote templatetag which returns queryset based on ids. It works like that: <ul id="lot-images" class="thumb-uploaders"> {% if form.errors %} {% load load_form_objects %} {% load_form_objects lot_form.images as images %} {% for image in images %} {% if image %} <li> <input type="hidden" name="images" value="{{image.id}}"/> <div class="image"> <div class="mask"></div> <img src="{{ image.get_thumbnail_url }}" alt=""/> <a href="#" class="delete">Удалить</a> </div> </li> {% else %} <li><a class="upload-medium"></a></li> {% endif %} {% endfor %} {% else %} <li><a class="upload-medium"></a></li> <li><a class="upload-medium"></a></li> <li><a class="upload-medium"></a></li> <li><a class="upload-medium"></a></li> <li><a class="upload-medium"></a></li> {% endif %} </ul>

  • m2m
  • form
  • errors
Read More

utf8-friendly dumpdata management command (no escape symbols)

Adds `--pretty` option to django `./manage.py dumpdata` command, which produces pretty utf8 strings instead of ugly unicode-escaped shit: $ ./manage.py dumpdata app.pricingplan --indent=1 [ { "pk": 1, "model": "app.pricingplan", "fields": { "name": "\u0411\u0430\u0437\u043e\u0432\u044b\u0439", } }, { "pk": 2, "model": "app.pricingplan", "fields": { "name": "\u0425\u0443\u044f\u0437\u043e\u0432\u044b\u0439", } } ]% ./manage.py dumpdata app.pricingplan --indent=1 --pretty [ { "pk": 1, "model": "app.pricingplan", "fields": { "name": "Базовый", } }, { "pk": 2, "model": "app.pricingplan", "fields": { "name": "Хуязовый", } } ]%

  • fixtures
  • management
  • dumpdata
Read More

Using the {% widthratio %} template tag with CSS to create a bar graph

The {% widthratio %} template tag is under appreciated! Here, it's combined with CSS to create a bar graphic for the results of an election (this example comes from [this page](http://flickr.com/photos/postneo/405239750/in/photostream/), but has been modified slightly for simplicity's sake). The widthratio tag can be used to create all sorts of graphs and charts, as well as things like tag clouds. Here, we pass it the number of votes for a candidate, the total number of votes in the election, and the integer 190, which is the width, in pixels, of a "full" bar on the bar graph. In other words, 100% = 190 pixels. It works great!

  • template
  • templatetag
  • widthratio
  • graph
  • infographic
Read More

UnitTesting without create/destroy database

This test runner is invoked with its own command: ./manage.py quicktest {usual test args follow} this creates a test database if it needs to and then DOES NOT delete it. subsequent uses of it start with the same database. this is for rapid test/development cycles usually running a single test. a single test can run in less than a second. when you need to alter the schema simply use the normal ./manage.py test which will delete the old test database and create a fresh one. it does not replace your normal test runner. it could probably be altered to even use your custom test runner. there are improvements to be done, and it will be included with a small testy app soon.

  • unittest
Read More

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

fancy_if

I am working on some apps that use row level permissions. For many permission tests I intend to make custom tags so I can locate the permission test used by the template and by the view in a common module. However, frequently, before I decide what the actual end-tag is going to be I need a way to expression a more powerful 'if' structure in the template language. Frequently the existing if and if_has_perm tags are just not powerful enough to express these things. This may make the template language unacceptably more like a programming language but it has helped me quickly modify complex permission statements without having to next and repeat four or five clauses. As you can see this is intended to work with django off of the row level permissions branch. Here is an example of a template that is using the 'fancy_if' statement: ` {% fancy_if or ( and not discussion.locked not discussion.closed "asforums.post_discussion" discussion ) "asforums.moderate_forum" discussion.forum %} <li><a href="./create_post/?in_reply_to={{ post.id }}">{% icon "comment_add" "Reply to post" %}</a></li> {% end_fancy_if %} {% fancy_if or "asforums.moderate_forum" discussion.forum ( and not discussion.closed ( or eq post.author user eq discussion.author user ) ) %} {% fancy_if or "asforums.moderate_forum" discussion.forum eq post.author user %} <li><a href="{{ post.get_absolute_url }}update/">{% icon "comment_edit" "Edit Post" %}</a></li> {% end_fancy_if %} <li><a href="{{ post.get_absolute_url }}delete/">{% icon "comment_delete" "Delete Post" %}</a></li> {% end_fancy_if %} `

  • row-level-permissions
  • compound-conditional
Read More

South introspection rules for TimeZoneFields

TimeZoneField is not supported with South 0.7. This snippet adds a custom rule to the introspection rules for TimeZoneField. The code is found in the following thread, and fixed according to the latest version of TimeZoneField. http://groups.google.com/group/south-users/browse_thread/thread/34a05331140ee4dd **Usage** Simplest way is to save this snippet in a south_rules.py file and add an import in the models.py.

  • timezones
  • south
  • timezonefield
Read More

Currency formatting filter

See the function **docstring** for usage. This template filter has a couple of drawbacks: * Uses **locale.setlocale** which, according to the [Python docs](http://docs.python.org/library/locale.html#locale.setlocale), is not thread safe. I don't know how this may affect Django applications. * Requires Python 2.5+. Updated 2011-03-16.

  • template
  • filter
  • currency
  • formatting
Read More

TinyMCE Widget

Widget for TinyMCE 3.2.6, a WYSIWYG HTML editor for `textarea`. **Note:** > This snippet uses the TinyMCE package thats contains special jQuery build of TinyMCE and a jQuery integration plugin. Anyway, is easily to adapt to standard package. Usage example: from django.contrib.flatpages.admin import FlatpageForm class MyFlatPageForm(FlatpageForm): content = forms.CharField(widget=TinyMCEEditor()) [TinyMCE download page](http://tinymce.moxiecode.com/download.php)

  • forms
  • wysiwyg
  • form
  • widget
  • modelform
  • tinymce
Read More

Extended db cache backend with 'filter() / LIKE' support (and now scheduled cache clean!)

Because the db caching doesn't support atomic operations, it was unsafe to store a list of 'keys' in a single key. So, rather than store the list, I just append each key with a specific tag, and then filter for it later. This means I don't need to worry too much about atomic usage with lists (i.e. queued requests). However - I still can think of many instances where I would need atomic usage, so I will probably implement this later on down the line. Hopefully, the atomic modifications will be accepted by the core devs. This also contains threaded cache cleaning, which means you no longer need to rely on requests to clean the cache (which would have potentially slowed the user query down), and will remove any cache entries past their expiry date every 3 minutes. Enjoy! Cal

  • filter
  • cache
  • db
  • backend
  • like
Read More