Login

All snippets

Snippet List

State Machine inspired by acts_as_state_machine

A quick and dirty state machine inspired by the rails plugin, acts_as_state_machine. When implementing this on a model, the model is expected to have a character field in the database called "state." Next, come up with a few states that a model can be in and initialize a machine object with those states. Now you need to define the way a model moves from one state to the next. You do this by calling the 'event' method on the machine object. The first event argument defines the name of the method which will transition you to the next (to) state. The next argument is a dictionary defining what the current state must be in order to transition to the ending state. So, in the example, an Entry can transition from any state (the '*') to the draft state by calling entry.draft(). An entry can also transition from the 'draft' or 'hidden' state to the 'published' state which is enforced when calling entry.publish(). You can see what state a model object is in by calling <model_object>.state but sometimes it is more desirable to explicitly ask if a model object is in a particular state; this is done by the calling <model_object>.is_published() or <model_object>.is_draft(). All the code does is prefix "is_" to the "to" state which returns a True or False if the model is in that particular state.

  • state-machine
Read More

get_queryset_or_404

Sometimes we want to get a queryset or 404, for example, if we're passing our queryset to a subclassed generic view. This is identical to get_list_or_404 but returns a queryset.

  • shortcut
  • template
  • queryset
  • get_queryset_or_404
  • get_list_or_404
Read More

SMTPConnection with Return-Path

Sometimes when sending email you want to specify a Return-Path different from the "From:" address on the email. The Return-Path is used for bounced email and is required for [VERP](http://en.wikipedia.org/wiki/VERP). This class overrides SMTPConnection so that you can specify return_path.

  • email
Read More
Author: sgb
  • 2
  • 3

exception handling middleware

<code> is_loaded = False if not is_loaded: is_loaded = True #... ExceptionHandlingMiddleware as EHM import views EHM.append(views.AuthFailError, views.auth_fail) # when AuthFailError thrown it redirects to `auth_fail` view function. </code>

  • middleware
  • error
  • exception
  • custom
  • handling
Read More

Conditional template parsing block

I'm developing a regionalization extension based on PostGIS and GeoDjango for a web-based LCA software. Because PostGIS (or PostgreSQL) is not available everywhere, we needed a way to fully disable the geographic extensions. Because of that, I set out to create a template block tag which only gets evaluated when GIS support is active and totally ignored (treated as a comment) otherwise. I had some problems getting my BoringNode to work (which should just pass the content through), so I've just used the AutoEscapeControlNode (why? Because it was the first usable class that jumped into my eye.) for this purpose.

  • template-tag
  • conditional-parsing
Read More
Author: mk
  • 0
  • 0

quick_url filter

A simple filter that generates a url from an object that has a get_absolute_url method. {{ object|quick_url }} a previous, simpler approach: [#511](http://www.djangosnippets.org/snippets/511/)

  • filter
  • get_absolute_url
  • quick_url
Read More

Template Filter attr

You can add this code to a file named "field_attrs.py" in a templatetags folder inside an application. To use it, remember to load the file with the following template tag: {% load field_attrs %} And for each field you want to change the widget's attr: {{ form.phone|attr:"style=width:143px;background-color:yellow"|attr:"size=30" }}

  • template
  • filter
  • newforms
  • forms
  • form
  • field
  • attr
Read More

Auto slug field

New field type which allows prepopulate_from to work not only from javascript but in python too. If the slugfield has unique=True creates a unique slug too.

  • slug
  • field
  • auto
  • prepopulate_from
Read More

Profiling middleware using cProfile

Similar to [Profiling Middleware](http://www.djangosnippets.org/snippets/186/), but uses cProfile instead of hotshot. Append ?prof to the URL to see profiling output instead of page output.

  • middleware
  • performance
  • profiler
Read More
Author: sgb
  • 5
  • 24

Google Charts Templatetags (HTML)

Example usage of the GChartWrapper.charts module for creating dynamic charts with templatetags. It is an easy method of creating dynamic GoogleCharts from the [GoogleChartAPI](http://code.google.com/apis/chart/). The project is located at [google-chartwrapper](http://code.google.com/p/google-chartwrapper/). To get the most recent version: `svn checkout http://google-chartwrapper.googlecode.com/svn/trunk/` and run `python setup.py` in the downloaded trunk directory. There is an included django project there with the [ChartsExamples](http://code.google.com/p/google-chartwrapper/wiki/ChartExamples) all worked out in django templates

  • templatetags
  • google
  • chart
Read More

User/IP Banning Middleware

Banning middleware with allow,deny functionality. Can select by User id/username and IP addresses. Returns a HttpResponseForbidden when banning requests. Banning by users is real nice because no matter which IP a pest comes from, they can never retrieve anything that they log into. Very handy for keeping out those unwanted pests! I personally developed this further to use a Ban model to keep track of different bans on different sites. Maybe ill post that eventually, but this runs as is with static vars. Implementation from [HvZ Source](http://www.hvzsource.com)

  • middleware
  • python
  • ban
Read More

Character encoding fix

There is a commonly encountered problem with Django and character sets. Windows applications such as Word/Outlook add characters that are not valid ISO-8859-1 and this results in problems saving a Django model to a database with a Latin 1 encoding. These characters should also be converted to avoid any display issues for the end users even if you are using a UTF-8 database encoding. The topic is well covered at [Effbot](http://effbot.org/zone/unicode-gremlins.htm) and contains a list of appropriate conversions for each of hte problem characters. Correcting this for all of your Django models is another issue. Do you handle the re-encoding during the form validation? The save for each model? Create a base class that all your models need to inherit from? The simplest solution I have created leverages [Signals](http://code.djangoproject.com/wiki/Signals) Combining the re-encoding method suggested at Effbot and the pre_save signal gives you the ability to convert all the problem characters right before the save occurs for any model. **kill_gremlins method replaced with Gabor's suggestion**

  • django
  • python
  • unicode
  • latin1
  • character
  • encoding
Read More

Username genrator

This function generate an username based on the user's full name. First it tries to use the first name first letter plus the last name, second it tires the first name plus the last name first latter, and at last it tries to use the first name with a sequential number at the end. The username generated are all lowercase and ASCII only characters.

  • auth
  • username
  • name
Read More

3109 snippets posted so far.