Login

All snippets written in Python

Snippet List

Middleware to remove the WWW from the URL

Works like the [PREPEND_WWW](http://www.djangoproject.com/documentation/settings/#prepend-www) setting but, instead of adding, it removes the www. Usage: In the settings file add the UrlMiddleware to the middleware list and set REMOVE_WWW = True

  • middleware
Read More

Searchable Media

This app allows you to utilize mysql's fulltext searching over multiple models and multiple apps, letting the site search seem more intuitive, yet still allow your content to be very structured. Essentially, it creates an entire new model that associates objects to a chunk of text to search efficiently over (and index), using the contenttypes app. Simply add the post_save events to your existing models for things you want to be searched.

  • search
  • media
  • fulltext
  • mixed
Read More

Alternative to User.get_profile()

**This is an alternative to User.get_profile.** Rather than having you call `User.get_profile` directly, this retrieves the profile instance for a `User` and attaches the fields from the profile to the `User` object when instantiated. The special methods for `DateField`, `FileField`, `ImageField` and fields with `choices` are also created. Since the profile object still has to be retrieved from the database before its fields can be added to the `User`, the costs for using this might outweigh the rewards unless you are heavily using profiles. To install, place it in a module on your `PYTHONPATH` and add it to `INSTALLED_APPS`.

  • user
  • profile
  • auth
  • userprofile
  • profiles
Read More

Simple Exception Response for AJAX debugging

When debugging AJAX with Firebug, if a response is 500, it is a pain to have to view the entire source of the pretty exception page. This is a simple middleware that just returns the exception without any markup. You can add this anywhere in your python path and then put it in you settings file. It will only unprettify your exceptions when there is a XMLHttpRequest header. Tested in FF2 with the YUI XHR. Comments welcome. EDIT: I recently changed the request checking to use the is_ajax() method. This gives you access to these simple exceptions for get requests as well (even though you could just point your browser there).

  • middleware
  • ajax
  • exception-handling
Read More

unique validation for ModelForm

Inherit your forms from model from this ModelForm and it will check all the database fields with unique=True in `is_valid()`. This is a hack around [#5736](http://code.djangoproject.com/ticket/5736). It is actually a part of a grand problem mentioned in [#4895](http://code.djangoproject.com/ticket/4895). You can use this hack until the issue is fully resolved.

  • newforms
Read More

djangoskel

Sometimes i like to try things out in a blank django project, so i created a python script which creates an out of the box working project skeleton for me: $ djangoskel.py project_name

  • project
  • skeleton
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

Raise Exception on invalid template variable

This recipe raises an exception if there is an invalid variable in the template. See [#6766](http://code.djangoproject.com/ticket/6766) Note: I don't need this snippet any more, since I don't use the template language any more. For my projects using only python is better (complex logic, simple layout).

  • template_string_if_invalid
Read More

CustomChoiceField, Selectable label field version of ModelChoiceField

**The problem** ModelChoiceField always uses __unicode__ or __str__ to fill the labels. I needed to dynamically select which field to use for the labels. **The solution** My approach copies a lot from [this blog](http://oebfare.com/blog/2008/feb/23/overriding-modelchoicefield-labels/) with some modifications to make it more dynamic. There are some proposals to fix on this [Ticket #4620]( http://code.djangoproject.com/ticket/4620) **How to use** Include the code on your forms.py (or whatever you are using) and use the CustomChoiceField with the extra argument label_field instead of ModelChoiceField. Hope it helps someone.

  • newforms
  • forms
  • modelchoicefield
  • modelform
Read More

Newforms field for decimals with a comma

This might be handy in countries where decimals are entered with a comma separating the decimal places from the integer part (for instance in Germany). It lets user enter and displays all decimals with a comma separator. I ran into this problem and couldn't find a clean internationalized way of doing it... but newforms makes it so easy to roll your own. Hope it helps someone.

  • newforms
  • locale
  • comma
  • decimal
Read More

chdjango

This is a convenient script for those working with different branches of Django. Place all of your branches in `~/django` (e.g., `~/django/newforms-admin`, `~/django/trunk`) and you're ready to quickly change between them. For example: `chdjango.py trunk`.

  • django
  • path
  • change
  • chdjango
  • branches
  • pth
  • site-packages
Read More

Q marshaller

Django supports the serializing model objects, but does not support the serializing Q object like that, ============================ q = Q(username__contains="findme") model0.objects.filter(q) serialize(q) # X ============================ so I wrote a little marshaller for Q, this is example, ============================ from django.contrib.auth import models as django_models qs = django_query.Q(username__contains="spike") | django_query.Q(email__contains="spike") _m = QMarshaller() a = _m.dumps(qs) # a was serialized. When call the similiar queries in page by page, you don't need to write additional code for creating same Q(s) for filtering models, just use the serialized Q as http querystring and in the next page unserialize and apply it. That is simple life.

  • model
  • python
  • q
  • query
Read More

Log errors to a file

This is another example use of the [exception middleware](http://www.djangosnippets.org/snippets/638/). It shows how to log exceptions to a file. Someone wanted to do this to avoid DOS-ing the email server in case of a silly error. (untested.)

  • middleware
  • log
  • error
  • exception
  • file
Read More

Extensible exception handling middleware

This exception middleware abstracts the functionality of the builtin exception handling mechanisms, but makes them extensible by inheritance. Just add it (or some subclass) to the top of your active middleware list. You can use this to [make your admin emails more informative](http://www.djangosnippets.org/snippets/631/) or [log errors to a file](http://www.djangosnippets.org/snippets/639/).

  • middleware
  • exception
Read More

2956 snippets posted so far.