Login

Top-rated snippets

Snippet List

Update All Apps to Latest Revision

This snippet is based on [#844](http://www.djangosnippets.org/snippets/844/) and updates all apps in the current directory using hg, svn, git or bzr.

  • update
  • svn
  • git
  • hg
  • bzr
Read More

Template tag: split list to n sublists

Based on [this snippet](http://www.djangosnippets.org/snippets/660/), adapted to split a list into *n* number of sublists, e.g. split a list of results into three evenly-divided sublists to enable display of the results in three columns on one page with CSS. Tag: `{% list_to_columns your_list as new_list number_of_columns %}` The split_seq solution comes from a comment by Sebastian Hempel on [this post](http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425397). More info [here](http://herself.movielady.net/2008/07/16/split-list-to-columns-django-template-tag/).

  • template
  • list
  • template-tags
Read More

PositionField

**This is a model field for managing user-specified positions.** Usage ===== Add a `PositionField` to your model; that's just about it. If you want to work with all instances of the model as a single collection, there's nothing else required. In order to create collections based on another field in the model (a `ForeignKey`, for example), set `unique_for_field` to the name of the field. It's probably also a good idea to wrap the `save` method of your model in a transaction since it will trigger another query to reorder the other members of the collection. Here's a simple example: from django.db import models, transaction from positions.fields import PositionField class List(models.Model): name = models.CharField(max_length=50) class Item(models.Model): list = models.ForeignKey(List, db_index=True) name = models.CharField(max_length=50) position = PositionField(unique_for_field='list') # not required, but probably a good idea save = transaction.commit_on_success(models.Model.save) Indices ------- In general, the value assigned to a `PositionField` will be handled like a list index, to include negative values. Setting the position to `-2` will cause the item to be moved to the second position from the end of the collection -- unless, of course, the collection has fewer than two elements. Behavior varies from standard list indices when values greater than or less than the maximum or minimum positions are used. In those cases, the value is handled as being the same as the maximum or minimum position, respectively. `None` is also a special case that will cause an item to be moved to the last position in its collection. Limitations =========== * Unique constraints can't be applied to `PositionField` because they break the ability to update other items in a collection all at once. This one was a bit painful, because setting the constraint is probably the right thing to do from a database consistency perspective, but the overhead in additional queries was too much to bear. * After a position has been updated, other members of the collection are updated using a single SQL `UPDATE` statement, this means the `save` method of the other instances won't be called. More === More information, including an example app and tests, is available on [Google Code](http://code.google.com/p/django-positions/).

  • lists
  • models
  • fields
  • model
  • field
  • list
  • sorting
  • ordering
  • collection
  • collections
Read More

SSL Redirect Middleware

Snippet 240 is great, but it does not handle flatpages since flatpages are not technically a view. This operates on the request level, not the view level so it will handle flat pages. **Step 1** Add this class to your MIDDLEWARE_CLASSES **Step 2** Add an entry in settings.py which is a list of regex to match against urls that u want to have ssl: SSL_URLS = ( r'/login/', r'/home/', r'/super-sensitive-information/', )

  • middleware
  • ssl
  • redirect
Read More

Switch/case conditional tags

This tag allow you to use C-like switch tag in your templates. It is useful for sequencial and repetitive `{% ifequal %}` tags. To install it in your project, you just need to follow [these instructions](http://www.djangoproject.com/documentation/templates_python/#extending-the-template-system)

  • tag
  • conditional
  • switch
  • case
Read More

Owner required decorator

This decorator allows edit or delete for the owner of the record. Snippet applies for every model that has ForeignKey to User. Works for User model too. Works with other decorators as permission_required or similar. Decorator raise http 403 view if user is not owner. **Usage** @permission_required('blogs.change_entry') @owner_required(Entry) def manage_entry(request, object_id=None, object=None): Decorator populates object kwargs if object_id present, otherwise just returns original view function. @permission_required('blogs.delete_entry') @owner_required() def entry_delete(*args, **kwargs): kwargs["post_delete_redirect"] = reverse('manage_blogs') return delete_object(*args, **kwargs) In generic delete wrapper view returns original view function.

  • decorator
Read More

YouTube Template Filter

Given a youtube url (can copy and paste right from the browser) turns the url into an embedded video. If you put this in your app's templatetags/filters.py, you can do the following >{{ object.youtube_url|youtube }} and it would embed the youtube video.

  • template
  • filter
  • youtube
  • embed
Read More

(en-US) Humanized Decimal Field

Simple DecimalField class extension that automatically adds formatting and validation for comma-separated "decimals". Works wonderfully for price fields. Could be extended to strip dollar signs or to be locale-agnostic.

  • form
  • humanize
  • field
  • comma
  • decimal
  • thousands
  • separator
  • input
Read More

ActiveManager: filter objects depending on publication and/or expiration dates

This manager is intended for use with models with publication and/or expiration dates. Objects will be retrieved only if their publication and/or expiration dates are within the current date. Use is very simple: class ExampleModel(models.Model): publish_date = models.DateTimeField() expire_date = models.DateTimeField(blank=True, null=True) objects = models.Manager() actives = ActiveManager(from_date='publish_date', to_date='expire_date') ExampleModel.actives.all() # retrieve active objects according to the current date The manager works correctly with nullable date fields. A null publication date means "*always published (until expiration date)*" and a null expiration date means "*never expires*". Most models should define the `objects` manager as the default manager, because otherwise out of date objects won't appear in the admin app.

  • model
  • manager
  • active
  • publication
  • expiration
  • date-filter
Read More

SectionedForm

Sometimes we need divide forms in fieldsets, but this make us declare all fields in HTML template manually. This class is to help you to do this by a easy way. **How to use** First, download this file as name "sectioned_form.py" Later, turn your form inherited from the class **SectionedForm**, override method "_html_output" and declare fieldsets and fieldset_template attribute, like below: from sectioned_form import SectionedForm class MyForm(forms.ModelForm, SectionedForm): fieldsets = ( (None, ('name','age','date')), (_('Documents'), ('number','doc_id')), ) fieldset_template = "<h2>%s</h2>" def _html_output(self, *args, **kwargs): return SectionedForm._html_output(self, *args, **kwargs)

  • newforms
  • forms
  • form
  • formset
Read More

Timing Django Requests

Adds an 'X-Django-Request-Time' HTTP response header that times how long django spent processing the request.

  • middleware
  • http
  • headers
  • profiling
Read More

Django newforms ExtJS JSON Encoder

This is a subclass of Django's built-in JSONEncoder that adds the ability to output form and field objects as ExtJS-compatible config objects. Simple example: from django.utils import simplejson json = { 'data': [], 'success': True, 'metaData': { 'fields': SFY09RDOForm(), 'root': 'data', 'successProperty': 'success' }, } return HttpResponse(simplejson.dumps(json, cls=ExtJSONEncoder)) Where SFY09RDOForm is a subclass of django.forms.Form. 6/20/2008: Updated to pass on the help_text parameter (useful in combination with this override in ext: http://extjs.com/forum/showthread.php?t=36642)

  • json
  • ext
  • encoder
  • extjs
Read More

RandomFileExtensionMiddleware

If you feel nostalgic for the old days of crufty URLs, put this middleware somewhere in your Django app and add the first entry in settings.MIDDLEWARE_CLASSES as shown below. Keep in mind that you need to replace 'path.to' with the correct Python path to the middleware. MIDDLEWARE_CLASSES = ( 'path.to.RandomFileExtensionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ) Note: Although this works it's still a joke.

  • middleware
Read More

3110 snippets posted so far.