Login

Top-rated snippets

Snippet List

Require login by url

An example of using it in your settings.py: MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware', 'util.loginmiddleware.RequireLoginMiddleware', ) LOGIN_REQUIRED_URLS = ( r'/payment/(.*)$', r'/accounts/home/(.*)$', r'/accounts/edit-account/(.*)$', ) In a nutshell this requires the user to login for any url that matches against whats listing in LOGIN_REQUIRED_URLS. The system will redirect to [LOGIN_URL](http://www.djangoproject.com/documentation/settings/#login-url)

  • middleware
  • authentication
  • url
  • login
  • auth
Read More

Expire page from cache

A simple helper function that clears the cache for a given URL, assuming no headers. Probably best used when wired up to a model's post_save event via signals. See [message to django-users mailing list](http://groups.google.com/group/django-users/msg/b077ec2e97697601) for background.

  • cache
  • caching
  • expiration
Read More

Enumeration field

These three classes allows you to use enumerations (choices) in more natural model-like style. You haven't to use any magic numbers to set/get field value. And if you would like to make your enumeration a full-fledged django-model, migration should be easy. Note, that you can subclass Item to add some context-specific attributes to it, such as `get_absolute_url()` method for instance. Examples are provided in the form of `doctest` in the second half of the snippet.

  • newforms
  • choice
  • model
  • field
Read More

in_group template filter

Allows you to search if a user belongs to a given group. Along the same lines as snippet [390](http://www.djangosnippets.org/snippets/390/), but uses a regular ``if`` tag so it is more flexible. (Updated for efficiency. Running a boolean test on a QuerySet avoids a bit of unnecessary overhead.) (Updated to accept a list of groups.)

  • template
  • filter
  • group
Read More

Django and Twill

Django's test client is very limited when it comes to testing complex interactions e.g. forms with hidden or persisted values etc. Twill excels in this area, and thankfully it is very easy to integrate it. * Use `twill_setup` in your `TestCaseSubClass.setUp()` method * Use `twill_teardown` in `TestCaseSubClass.tearDown()` method * In a test, use something like `make_twill_url()` to generate URLs that will work for twill. * Use `twill.commands.go()` etc. to control twill, or use `twill.execute_string()` or `twill.execute_script()`. * Add `twill.set_output(StringIO())` to suppress twill output * If you want to write half the test, then use twill interactively to write the rest as a twill script, use the example in `unfinished_test()` Twill will raise exceptions if commands fail. This means you will get 'E' for error, rather than 'F' for fail in the test output. If necessary, it wouldn't be hard to wrap the twill commands to flag failure with TestCase.assert_ There are, of course, more advanced ways of using these functions (e.g. a mixin that does the setup/teardown for you), but the basic functions needed are here. See also: * [Twill](http://twill.idyll.org/) * [Twill Python API](http://twill.idyll.org/python-api.html)

  • testing
  • tests
  • twill
Read More

Use MEDIA_URL in flatpages

This is a template filter to enable the use of the MEDIA_URL setting in content from the flatpages database table. It searches for {{ MEDIA_URL }} and replaces it with that found in your settings. Note: To set up, drop the above code into a file called `media_url.py` in your templatetags directory in one of your INSTALLED_APPS, and add the filter to your flatpages template like so: {% load media_url %} {{ flatpage.content|media_url }}

  • filter
  • flatpages
Read More

Stateful paginator, digg style

**This code will throw deprecation warnings in newer Django checkouts - see the http://www.djangosnippets.org/snippets/773/ for an improved version that should work with the recent trunk.** objects = MyModel.objects.all() paginator = DiggPaginator(objects, 10, body=6, padding=2, page=7) return render_to_response('template.html', {'paginator': paginator} {% if paginator.has_next %}{# pagelink paginator.next #}{% endif %} {% for page in paginator.page_range %} {% if not page %} ... {% else %}{# pagelink page #} {% endif %} {% endfor %} http://blog.elsdoerfer.name/2008/03/06/yet-another-paginator-digg-style/

  • pagination
  • paginator
  • digg
Read More

Group results by a range of values in admin sidebar

Adds filtering by ranges of values in the admin filter sidebar. This allows rows in numerical fields to be grouped together (in this case, group by price): By store price All < 100 100 - 200 200 - 500 500 - 2000 >= 200 **To use:** 1. save the code as rangevaluesfilterspec.py in your app's directory 2. add `import rangevaluesfilterspec` to your models.py 3. add `myfield.list_filter_range = [value1, value2, ...]` to your filter field **Example:** from django.db import models import rangevaluesfilterspec class Product(models.Model): store_price = models.DecimalField(max_digits=10, decimal_places=2) store_price.list_filter_range = [100, 200, 500, 2000] class Admin: list_filter = ['store_price'] Note that two extra groups are added: less-than the lowest value, and greater-than-or-equal-to the highest value.

  • filter
  • admin
  • sidebar
Read More

Admin list_display Ajax

Sometimes it can be time consuming to go through a bunch of objects in Django's Admin if you only need to update one field in each. An example of this is an `order` field that allows you to manually set the order for a queryset. **This snippet contains examples of how to set up the Admin list_display to make Ajax calls to a custom view.** The following code may not be worthy of being a snippet, it's all pretty straightforward, but here it is for those who just want to copy-and-paste.

  • admin
  • jquery
Read More

Auto rendering decorator with options

This view decorator renders automaticaly the template with the context provided both by the view "return" statement. For example: @auto_render def my_view(request): ... return 'base.html', locals() You can still return HttpResponse and HttpResponseRedirect objects without any problems. If you use Ajax requests, this decorator is even more useful. Imagine this layout: def aggregating_view(request): ... context = locals() partial1 = partial_view_1(request, only_context=True) partial2 = partial_view_2(request, only_context=True) # aggregate template include partial templates return 'aggregate.htmt', context.update(partial1).update(partial2) def partial_view_1(request): ... return 'partial_1.html', locals() def partial_view_2(request): ... return 'partial_2.html', locals() This way you can render you view individualy for specific ajax calls and also get their context for the aggregating view.

  • render_to_response
  • ajax
  • decorator
  • rendering
Read More

Autoload Django Models When Using ./manage.py shell

It's a pain to import all the Django models you want to use in the Python shell every time you start it. Here's how you can get IPython to autoload all your Django models for you every time you start the shell using ./manage.py shell. Put the code in a .py file in the root of your project. Then tell IPython to load the script in ~/.ipython/ipythonrc in the "Python files to load and execute" section.

  • import
  • shell
  • interpreter
  • autoload
Read More

Template tag: Extend with parameters

Extended extends tag that supports passing parameters, which will be made available in the context of the extended template (and all the way up the hierarchy). It wraps around the orginal extends tag, to avoid code duplication, and to not miss out on possible future django enhancements. Note: The current implementation will override variables passed from your view, too, so be careful. Some of the argument parsing code is based on: http://www.djangosnippets.org/snippets/11/ Examples: {% xextends "some.html" %} {% xextends "some.html" with title="title1" %} {% xextends "some.html" with title="title2"|capfirst %}

  • template
  • templatetag
  • extends
  • parameters
Read More

Instance partial update

If you're like me, you've got a models with a lot of fields/foreignkeys and often only want to edit a portion of the model in a form. Add this method to your custom form class and use it in place of the save() method.

  • forms
  • model
  • partial
  • updating
Read More

Templatetag for JS merging and compression

**Javascript merging and compression templatetag** One of the most important things for improving web performance is to reduce the number of HTTP requests. This is a templatetag that merges several javascript files (compressing its code) into only one javascript. It checks if this merged file is up to date, comparing modification time with the other javascripts to merge. Usage: {% load jsmerge %} {% jsmerge mergedfile js/file1.js js/file2.js js/file3.js %} The previous code will: 1. Search in `settings.MEDIA_ROOT` for all files passed by parameter. 2. Create a `/path/to/media_root/mergedfile.js` (if it doesn't exist or it's not up to date). This file is a merging plus compression of all javascripts. 3. Return this HTML fragment: `<script type="text/javascript" src="/media_url/mergedfile.js"></script>`

  • javascript
  • merging
  • compression
  • tunning
Read More

3110 snippets posted so far.