Login

Top-rated snippets

Snippet List

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

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

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

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

Testing with unmanaged models

Many of my projects heavily depend on other non-django projects to create the databases. To simplify setting up a test environment, I modified the simple test runner so that it will treat all models as managed. This will also allow for easier test set up against models that point to views. You can directly populate the view with the specific data needed for the tests, instead of populating (potentially) several models.

  • model
  • test
  • managed
Read More

Template-Filter for Feedparser-Dates

A filter that changes a preparsed date from [Ultimate Feedparser](http://www.feedparser.org/) to a regular datetime instance. Now you can -for example- pass a feed parsed by feedparser to a template and do this: {% for item in feed.entries %} Title: {{ item.title }}<br /> Date: {{ item.updated_parsed|feedparsed|date:"Y-m-d" }} {% endfor %}

  • template-filter
  • datetime
  • date
  • feedparser
Read More

Templatetag for granular permissions

If you're using [Django granular permissions](http://code.google.com/p/django-granular-permissions/), this templatetag may be useful. It enables you to check permission in templates, as mentioned in the code: {% has_row_perm user object "staff" as some_var %} {% if some_var %} ... {% endif %} To be used in `if` statements, it always saves the result to the indicated context variable. Put the snippet in row_perms.py in yourapp.templatetags package, and use `{% load row_perms %}` at your template.

  • template
  • templatetag
Read More

Automating URLs

This might be a bit cludgy. But the idea is to extend model definition with mixins that can help with defining standard views. So defining a new model as inheriting from Model and All, would allow automatic definition of /get /post type accessors.

  • rest
  • url
Read More

Using class methods as views

This set of handlers allow one to isolate requests based on the method posted. Normally, in a view, we would do checks for request.method value and update the resource accordingly. This makes the view code pretty messy. So one way to avoid these check each time is to have a handler method (resource_handler above), that checks for the method parameter and dispatches to the handler withe the prefix <method>_handler_<suffix>. This also has the advantage of grouping related actions in a particular class. At the same time a new instance of the request handler is not created on each request (as with the google appengine handler?). Yet another advantage is by making the handler methods as class methods, the handler classes can be inherited to add further functionality to a resource "group. The disadvantage however is the inability to restrict access to a handler method to only particular methods. Eg above the "r'obja/(?P<id>[^\/]+)/delete/" would map to the delete_handler_objects if themethod was "delete" and post_handler_objects if the method was "post". However this can be worked with a different suffix passed to the handler_params method. Infact setting the suffix to "objects_delete" would result in a "delete_handler_objects_delete" handler on delete method and a Http404 on all others. Another inconvinience is the inability to detect a view handler by simply inspecting the url patterns. However, this information is carried within the handler_suffix and handler_class parameters which may infact provide greater insight into the semantics around the view handlers. Needless to say, this easily extends rest based accesses. Would greatly appreciate feedback and improvements.

  • django
  • views
  • class
  • methods
Read More

Text replacement with alternative font faces

Complex of tags and filters for easy replacement of text with alternative font faces. For browsers, who doesn`t support it by themselves. Templatetag code and documentation at [GitHub of django-headline](http://github.com/SkAZi/django-headline).

  • text
  • fonts
  • font
  • replacement
Read More

Template tag to create mailto links with options

A {% mailto %}{% endmailto %} template tag that requires an e-mail destination and optionally accepts subject, cc and bcc. It will then wrap whatever is within the tag in an `<a href="mailto:..."> </a>` HTML tag. See the docstring in the code for the {% mailto %} usage and some examples. You will need to load this template tag to your template. You can find detailed instructions [here](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#code-layout). But in a nutshell: 1. Create a templatetags package (meaning a directory with a __init__.py file in it) on the same level as your application's model.py 2. Put the code for this tag in a module (example: extra_tags.py) 3. On your template use {% load extra_tags %} -- note: the app where the templatetags package was created needs to be in INSTALLED_APPS 4. Use {% mailto user.email 'You subject here for {{user.get_full_name}}' %}blah{% endmailto %} This is my first django template tag. I am also NOT tremendously experienced with Python. Criticism and corrections are more than welcome.

  • template
  • tag
  • templatetag
  • email
  • mailto
Read More

A smart trace() command

A number of people have kindly posted snippets on how to use pdb/ipdb with django. However, this only works when running the django development server. I thought it would be nice to have a trace() command that would turn into a no-op when the development server is not running, so you wouldn't have to worry about leaving trace() commands in your code if you want to quickly test with mod_wsgi or mod_python. The code above attempts (on Posix-like systems) to determine if the development server is running (by quickly checking if "manage.py runserver" is in the process list), and sets a DJANGO_SERVER setting appropriately. Then when you import the trace() method, it is defined as set_trace() if DJANGO_SERVER is True, or a no-op if DJANGO_SERVER is False. When you hit the trace() in pdb/ipdb, enter "u" to go up to the calling trace() statement.

  • debugging
Read More

Counter model - run multiple persistent counters

Sometimes you just need to count things (or create unique-for-your-application IDs). This model class allows you to run as many persistent counters as you like. Basic usage looks like this: >>> Counter.next() 0 >>> Counter.next() 1L >>> Counter.next() 2L That uses the "default" counter. If you want to create and use a different counter, pass its name as a string as the parameter to the method: >>> Counter.next('hello') 0 >>> Counter.next('hey') 0 >>> Counter.next('hello') 1L >>> Counter.next('hey') 1L >>> Counter.next('hey') 2L You can also get the value as hex (if you want slightly shorter IDs, for use in URLs for example): >>> Counter.next_hex('some-counter-that-is-quite-high') 40e

  • database
  • counters
Read More

elif for smart if tag

The code posted here adds "elif" functionality to the [smart if snippet 1350](http://www.djangosnippets.org/snippets/1350/). To use the snippet first follow the instructions for installing smart_if, then swap in the method shown on the left for the original smart_if method. You'll need to keep all the supporting classes from the original implementation, of course. You can use it like this: {% if 0 %} {% if 1 %} Hello Venus {% else %} unexpected {% endif %} {% elif 0 %} Hello Earth {% elif 0 %} Foo {% else %} Hello Mars {% endif %} The code is compatible with original smart_if classes as of June 2009, and the use of "__contains__" in the Enders class relies on the current implementation of Parser.parse, which says "if token.contents in parse_until:" in the one place it uses the parse_until parameter, which seems like stable code to me. The code works by recursively creating SmartIfNodes for the elif clauses.

  • template
  • smart_if
Read More

3110 snippets posted so far.