Login

All snippets

Snippet List

optparse dic action

An optparse action that let's you accept any parameters from the commandline. It stores them in another dictionary, inside the final options.

  • python
  • optparse
Read More

Auto-resolving a specific object from key string in url with decorator

If you use decorators to views, it will greatly improve readability and extensibility of your code. I'm using a couple of decorators like this to reduce complexity and redundancy in my view codes. `wraps` from Python 2.5's standard library make the attributes (name, docstring, and etc) of the decorated function same to those of `view_func` so that it could be easily recognized when you run `./manage.py show_urls` or debug.

  • views
  • decorator
Read More

Template tag: Last x twitter msgs of user

A template tag which returns the n last tweets of a given user. It uses the twitter python lib. {% get_twitter_messages user foo limit 5 as tweets %} {% for tweet in tweets %} {{ tweet.text }} {{ tweet.time }} {{ tweet.url }} {% endfor %}

  • templatetag
  • twitter
Read More

improved sortby template tag

Variation on dictsort using attribute access. Nested attributes can be used, like, "obj.attr.attr_attr" Example usage: {% for entry in entries|sortby:'category.title' %} Based on [1609](http://www.djangosnippets.org/snippets/1609/)

  • template
  • tag
  • dictsort
Read More

Active User Sorted ModelAdmin

Since r7806, the `User` field is unsorted which makes it harder to find specific users in the list if there is more than a few. This snippet is an `django.contrib.admin.ModelAdmin` subclass which searches through all of the fields on a form and automatically sorts fields which have a relation with `User`. It also filters on having `active=True`. Just import the `SortedActiveUserModelAdmin` class in your `admin.py` and subclass your `ModelAdmin` classes from it instead of `admin.ModelAdmin`.

  • sorting
  • modeladmin
  • user-foreign-key
Read More

Improved model select field for generic relationships

Browse through the installed models using the content types framework. There are two difference in behavior with respect to the default field: 1. if a model provides a translation for its name (e.g.: verbose_name and/or verbose_name_plural), it shows that rather than a raw model name 2. allow to filter the models shown through the use of `choice` parameter Example: `mbf = ModelBrowseField(choices=['User', 'Session'])`

  • models
  • form
  • field
  • contenttypes
  • translation
  • browse
Read More

Export Related as JSON Admin Action

[The Django Admin Action documentation leads you through exporting a queryset to JSON](http://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#actions-that-provide-intermediate-pages). However exporting from a single model rarely tells the whole story. Using the CollectObjects class, `export_related_as_json` gathers all instances related by foreign keys to what is being exported and exports them as well in a serialization bonanza. Use it to export Users and you'll get their Profile objects as well! **Usage** # admin.py from django.contrib import admin admin.site.add_action(export_related_as_json)

  • serialize
  • admin
  • json
  • export
  • admin-action
Read More

Dynamically change a form select widget to a hidden widget

This is an example of how you change a ChoiceField select widget into a hidden field if the right GET variable is passed. In this example code it would change the select widget into something like the following if something like "?d=3" was passed. `<p><label for="id_designation">Designation</label>Designation Option<input type="hidden" name="designation" value="3" id="id_designation" /></p>`

  • dynamic
  • forms
  • select
  • hidden
  • widget
Read More

sortby template tag

This is a variation on dictsort that assumes objects with attributes, not dictionaries. Example usage: {% for book in author.book_set.all|sortby:'title' %}

  • template
  • dictsort
Read More

automating twitter

Assume you have a model called Delegate and you want to tweet whenever a new Delegate registers, the code above will do this. You need to install python-twitter.

  • twitter
Read More

Ensure ugettext is available absolutely everywhere

Put this into the __init.py__ file in the root of your project (the same directory level as urls.py and settings.py) and this installs _() as a global reference into the current running python VM, and now it’s as universally available as int(), map(), or str(). This is, of course, controversial. Modifying the python global namespace to add a function can be considered maintenance-hostile. But the gettext feature is so universal– at least to me– that __init__.py is where it belongs.

  • internationalization
  • gettext
Read More

RequestMiddleware

Add RequestMiddleware to your MIDDLEWARE_CLASSES settings Then, when you need request in special cases, call get_request(), which returns the request object. This has to be used in very special cases.

  • middleware
  • threading
  • request
  • local
Read More

Profanity Function (Disemvowel)

A better way of dealing w/profanity - disemvowel it! From [Wikipedia](http://en.wikipedia.org/wiki/Disemvoweling), "disemvoweling is a technique used to censor unwanted postings such as spam, internet trolling, rudeness or criticism and yet maintain some transparency, both of the act and the underlying word." Credit: Boing Boing Example: This original sentence: In the fields of Internet discussion and forum moderation, disemvoweling (also spelled disemvowelling) is the removal of vowels from text. would be disemvowelled to look like this: n th flds f ntrnt dscssn nd frm mdrtn, dsmvwlng (ls splld dsmvwllng) s th rmvl f vwls frm txt. Usage: body_input = form.cleaned_data["body"] body_input = disemvowel_profanity(body_input)

  • profanity
  • disemvowel
Read More

Ensure submitted slugs do not conflict with existing resolvable URLs

This code overrides the existing RegistrationForm in django-registration and adds a new validation step. In this step, the username (my example slug) is compared against all the existing URLs that the application currently resolves and, if it *does* successfully resolve, throws a validation exception. This indicates that the username chosen would be overriden (or, if you wrote your urls.py file badly, would override) an existing URL already recognized by your application. A much longer explanation can be found at [Dynamic names as first-level URL path objects in Django](http://www.elfsternberg.com/2009/06/26/dynamic-names-as-first-level-url-path-objects-in-django/).

  • registration
  • slug
  • reverse
  • resolve
Read More

3110 snippets posted so far.