Login

All snippets written in Python

Snippet List

Parse TemplateTag Variables Safely

Often times I want to be able to interchangeably pass either literal strings or context variables to a custom templatetag. This function first checks a string for the existence of surrounding quotes and uses the string inside. If the string didn't explicitly use quotes it checks to see if it can resolve the string as a context variable. As a fallback the function will simply return the full string. Example: {% get_latest_by_tag 'django' %} {% get_latest_by_tag object.tag %}

  • templatetag
Read More

ModelForm-based create_update generic views

This is a ModelForms-based rewrite of the create_object and update_object generic views, with a few added features. The views now accept a "form_class" argument optionally in place of the "model" argument, so you can create and tweak your own ModelForm to pass in. They also accept a "pre_save" callback that can make any additional changes to the created or updated instance (based on request.user, for instance) before it is saved to the DB. Usage: just save the code in a file anywhere on the PythonPath and use the create_object and update_object functions as views in your urls.py.

  • newforms
  • views
  • generic
  • update
  • modelforms
  • create
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

Admob Ad Insertion Snippet

**Update**: [Django AdMob](http://github.com/johnboxall/django_admob/tree/master) pluggable app on github. Given a Django ``request`` object and dict of admob parameters returns a Admob ad. If no ad can be retrieved displays a one pixel Admob tracker image. For the future: * Make a template tag for this? * Filter out other unneeded META parameters for the admob_post dict?

  • admob
  • ad
  • ads
  • mobile
Read More

MarkdownTextField

A [common pattern in Django](http://code.djangoproject.com/wiki/UsingMarkup) is to create a TextField intended for Markdown text (i.e. description) and a companion non-editable TextField for storing the HTML version (i.e. description_html), so the Markdown converter need not be run for every page view. This snippet is a custom field which encapsulates this pattern in a single field which can automatically create and update its companion HTML field. Usage: class MyModel(models.Model): description = MarkdownTextField()

  • model
  • markdown
  • field
Read More

SSL Redirect Middleware and testing

While we're on the topic of SSLRedirect (See snippet 240 and 880) here's what I add to the end of my ssl middleware module, so that SSLRedirect wont break my automated testing. It simply creates a dummy middleware class that removes the SSL argument, but does not do any redirecting. If you were to simply remove the middleware from settings, the extra SSL argument will then get passed on to all the relevant views. Of course, you'll need to define a TESTING variable in settings, or change this to something else like settings.DEBUG. Having the separate variable for testing allows you to run your server in DEBUG mode without side effects like the change above.

  • middleware
  • ssl
  • testing
  • redirect
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

CustomQueryManager

A `models.Manager` subclass that helps to remove some of the boilerplate involved in creating managers from certain queries. Usually, a manager would be created by doing this: class MyManager(models.Manager): def get_query_set(self): return super(MyManager, self).get_query_set().filter(query=blah) Other managers may return other query sets, but this is especially useful as one may define queries on a table which would be used a lot. Since the only part that ever changes is the `query=blah` set of keyword arguments, I decided to abstract that into a class which, besides taking the repetition out of manager definition, allows them to be and'd and or'd in a manner similar to the `Q` objects used for complex database queries. `CustomQueryManager` instances may be defined in one of two ways. The first, more laborious but reusable manner, is to subclass it, like so: class MyManager(CustomQueryManager): query = Q(some=query) Then, `MyManager` is instantiated with no arguments on a model, like normal managers. This allows a query to be reused without extra typing and copying, and keeps code DRY. Another way to do this is to pass a `Q` object to the `__init__` method of the `CustomQueryManager` class itself, on the model. This would be done like so: class MyModel(models.Model): field1 = models.CharField(maxlength=100) field2 = models.PositiveIntegerField() my_mgr = CustomQueryManager(Q(field1='Hello, World')) This should mainly be used when a query is only used once, on a particular model. Either way, the definition of `__and__` and `__or__` methods on the `CustomQueryManager` class allow the use of the `&` and `|` operators on instances of the manager and on queries. For example: class Booking(models.Model): start_date = models.DateField() end_date = models.DateField() public = models.BooleanField() confirmed = models.BooleanField() public_bookings = CustomQueryManager(Q(public=True)) private_bookings = public_bookings.not_() confirmed_bookings = CustomQueryManager(Q(confirmed=True)) public_confirmed = public_bookings & confirmed_bookings public_unconfirmed = public_bookings & confirmed_bookings.not_() public_or_confirmed = public_bookings | confirmed_bookings public_past = public_bookings & Q(end_date__lt=models.LazyDate()) public_present = public_bookings & Q(start_date__lte=models.LazyDate(), end_date__gte=models.LazyDate()) public_future = public_bookings & Q(start_date__gt=models.LazyDate()) As you can see, `CustomQueryManager` instances can be manipulated much like `Q` objects, including combination, via `&` (and) and `|` (or), with other managers (currently only other `CustomQueryManager` instances) and even `Q` objects. This makes it easy to define a set of prepared queries on the set of data represented by a model, and removes a lot of the boilerplate of usual manager definition.

  • models
  • q
  • manager
  • query
  • custom
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

Command Line Script Launcher

I often write short test or development scripts that are intended as one-offs. I typically want to execute these scripts from the command line but am always forgetting the necessary steps to set up the Django environment [as described here][bennett]. This snippet allows you execute arbitrary Python scripts from the command line with the context of a given project: python manage.py execfile /path/to/some/script.py Add the code to a file named `execfile.py` within the `management/commands` directory of one of your apps ([see here][ref] for details). [ref]: http://www.djangoproject.com/documentation/django-admin/#customized-actions "Customized Actions" [bennett]: http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/ "Standalone Django Scripts"

  • script
  • management
  • execfile
Read More

More information about users and groups in user admin

Add-on for auth app of newforms-admin branch, adding more information about users and their groups at user and group list in admin interface. Also, nice example on customization of contributed django admin apps. It adds the following to the user list interface: fields for is_superuser and is_staff, last login time; by default, short names of groups user is in (mousehover to see full names) It adds the following to the to group list interface: list of users in your groups. To enable, just put it somewhere and import it from your main urls.py: import useradmin

  • admin
  • newforms-admin
  • customization
  • users
  • groups
  • roles
  • information
  • nfa
  • supervising
Read More

upload handler decorators

In an admin custom view I had the requirement to modify the upload handlers. However, the @staff_member_required locked the Files upload handlers as it uses the request.POST - see [Ticket 7654](http://code.djangoproject.com/ticket/7654). These decorators can be used before other decorators to allow setting of the upload handlers. Usage example: @upload_handlers_insert(0, QuotaUploadHandler) @staff_member_required def upload(request): pass

  • admin
  • decorator
  • file
  • uploadhandler
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

Dynamic Django settings context processor

Here's a nice way of easily passing only certain settings variables to the template. Because of the way Django looks up context processors, we need a little hack with sys.modules. The [blog entry is here](http://sciyoshi.com/blog/2008/jul/10/dynamic-django-settings-context-processor/).

  • dynamic
  • settings
  • context
  • processor
Read More

2956 snippets posted so far.