Login

All snippets written in Python

2956 snippets

Snippet List

Test Django against many Pythons and databases

I'm posting this here mostly because I need a more permanent home for this than my lappy's hard drive. I hope it's interesting to other people, though. Anyway - this script is what I use to test Django against multiple versions of Python and multiple databases. To actually run this you'll of course need Python 2.3, 2.4, and 2.5 installed along with MySQL, PostgreSQL, and sqlite3 -- and the associated database wrappers for all 3 Pythons. Yes, for the record, I've got all those things installed on my laptop. If you can somehow make that work, though, running this script will print out a nice little summary of what's failing against which versions of Python and which database. Run with `-v` to see the actual failures.

  • testing
Read More

Lorem Ipsum - Random content for your mockups

The loremipsum tag generates random content for use in mockups. It takes this content from Cicero's De finibus bonorum et malorum. By default you get a random number of paragraphs up to 6, but you can affect this behaviour by passing in parameters for quantity and units. Units can be "paragraphs" or "words"; the default is paragraphs. Quantity dictates the number of units returned. If your django.conf.settings.TEMPLATE_DEBUG is True, then no output is returned, so you should be OK in the event you leave the tag in a production template. Syntax: {% loremipsum %} {% loremipsum quantity="3" units="paragraphs" %} By leaving the behaviour as random, you can see how your layout handles varying amounts of content. Handy, especially for multi-column pages. [Here's a stoopid site](http://lakes.knoxzilla.com/) where I'm playing with random text, pictures, business listings, etc. I do plan to add a "corpus" parameter to allow you to put your own corpus between lorumipsum and endloremipsum tags and a template parameter to specify the corpus should come from a template, but this has suited me well thus far.

  • tag
  • lorem
  • ipsum
  • mockup
Read More

Using manager methods

This is part of the user-registration code used on this site (see [the django-registration project on Google Code](http://code.google.com/p/django-registration/) for full source code), and shows a couple of interesting tricks you can do with manager methods. In this case there's a separate `RegistrationProfile` model used to store an activation key and expiration time for a new user's account, and the manager provides a couple of useful methods for working with them: `create_inactive_user` creates a new user and a new `RegistrationProfile` and emails an activation link, `activate_user` knows how to activate a user's account, and `delete_expired_users` knows how to clean out old accounts that were never activated. Putting this code into custom manager methods helps a lot with re-use, because it means that this code doesn't have to be copied over into different views for each site which uses registration, and also makes more sense in terms of design, because these are methods which need to "know about" the model and work with it, and so they belong in a place close to the model.

  • managers
  • registration
Read More

Simple REST APIs

This is how I tend to roll simple REST APIs. It's by no means as full-featured as something like Piston, but it's simple, clean, and it works.

  • rest
Read More

WebFaction fixes middleware

On WebFaction, each host has it's own Apache instance, with WebFaction's main Apache instance forwarding requests. This is very useful but means that some of the original information is lost. This middleware should be installed at the top of your list to restore this lost info. It includes the functionality that used to be in SetRemoteAddrFromForwardedFor before it was removed from Django.

  • middleware
  • ssl
  • webfaction
  • https
Read More

MarkupField

This is a field that allows multiple markup types but also stores the pre-rendered result in the database which offers an advantage over calling one of the render methods each time. Example usage looks like: class BlogPost(models.Model): ... post = MarkupField() the various extra fields can then be accessed as follows: BlogPost.objects.get(pk=1).post # raw content BlogPost.objects.get(pk=1).post_markup_type # markup type (plain text, html, markdown, rest, textile) BlogPost.objects.get(pk=1).post_rendered # content of post rendered to html BlogPost.objects.get(pk=1).post_as_html # property that access post_rendered but marked safe for easy use in templates After writing my initial version of this I was pointed at the similar http://www.djangosnippets.org/snippets/1169/ I find mine a bit more useful as it includes ReST and includes a mark_safe call to allow showing the rendered HTML directly. I have however borrowed the nice idea of dynamically building MARKUP_TYPES from #1169. Also available via http://gist.github.com/67724.

  • fields
  • rest
  • markup
  • markdown
  • textile
  • restructuredtext
Read More
Author: jpt
  • 8
  • 16

Full-Text Searchable Models

A drop-in module to allow for full-text searchable models with very little effort. Tested with PostgreSQL 8.3, but should work on earlier versions with the tsearch2 module installed.

  • models
  • search
  • full-text
  • tsearch2
Read More

Easy file upload handler

This function emulates the file upload behaviour of django's admin, but can be used in any view. It takes a list of POST keys that represent uploaded files, and saves the files into a date-formatted directory in the same manner as a `FileField`'s `upload_to` argument.

  • image
  • forms
  • view
  • upload
  • imagefield
  • filefield
  • file
Read More

Model inheritance with content type and inheritance-aware manager

inspired by crucialfelix's [inheritance hack](http://www.djangosnippets.org/snippets/1031/), which was a far better method of fetching a model's subclassed version from an instance than my own, i decided to bake his snippet in to my own inheritance hack, which i think benefits both. the result is a query set that returns subclassed instances per default. So - in the snippet's example, querying `Meal.objects.all()[0]` will return a salad object, if that instance of Meal happens to be the parent of a Salad instance. To my mind this is closer to the 'intuitive' way for a query set on an inheriting model to behave. **Updated:** added subclassing behaviour for the iterator access as well. **Updated:** incorporated carljm's feedback on inheritance

  • manager
  • inheritance
Read More

Switch template tag

The `{% switch %}` tag compares a variable against one or more values in `{% case %}` tags, and outputs the contents of the matching block. An optional `{% else %}` tag sets off the default output if no matches could be found: {% switch result_count %} {% case 0 %} There are no search results. {% case 1 %} There is one search result. {% else %} Jackpot! Your search found {{ result_count }} results. {% endswitch %} Each `{% case %}` tag can take multiple values to compare the variable against: {% switch username %} {% case "Jim" "Bob" "Joe" %} Me old mate {{ username }}! How ya doin? {% else %} Hello {{ username }} {% endswitch %}

  • tag
  • templatetag
  • switch
Read More

Create variables within templates

Here is a Django template tag that allows you to create complex variables specified in JSON format within a template. It enables you to do stuff like: {% var as person %} { "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ "212 555-1234", "646 555-4567" ] } {% endvar %} <p>{{person.firstName}}, </br> {{person.address.postalCode}}, </br> {{person.phoneNumbers.1}} </p> This tag also enables me to do dynamic CSS using as follows: # urlpatters urlpatterns = patterns('', (r'^css/(?P<path>.*\.css)$', 'get_css'), ) #views def get_css(request, path): return render_to_response('css/%s' % path, {}, mimetype="text/css; charset=utf-8") # dynamic css within in /path/to/app/templates/css' {% load var %} {% var as col %} { "darkbg": "#999", "lightbg": "#666" } {% endvar %} {% var as dim %} { "thinmargin": "2em", "thickmargin": "10em" } {% endvar %} body { background: {{col.darkbg}}; margin: {{dim.thinmargin}}; }

  • tag
  • json
  • css
  • variables
  • var
Read More

Upload progress handler using cache framework

Ticket [#2070](http://code.djangoproject.com/ticket/2070) allows you to create your own file upload handlers. Here's an example handler that tracks a file's upload so you might display a progress meter after form submission. The snippet has two parts, the upload handler which tracks progress, and an upload_progress view used to report back to the browser. The upload handler uses [django's cache framework](http://www.djangoproject.com/documentation/cache/#the-low-level-cache-api) to store the data, which can then be retrieved by the view to send back to the browser. Note: Your form's http post request must have a query parameter (X-Progress-ID) sent along with it, which should contain a unique key to identify the upload. That key will also be sent with your ajax requests to the upload_progress view to retrieve the progress data. Setup: place the UploadProgressCachedHandler anywhere you like on the python path, and add to your settings.py: from django.conf import global_settings FILE_UPLOAD_HANDLERS = ('path.to.UploadProgressCachedHandler', ) + \ global_settings.FILE_UPLOAD_HANDLERS Set up the upload_progress view in any of your apps along with a corresponding entry in your urlconf. Here's some javascript example code to make the ajax requests and display the progress meter: <http://www.djangosnippets.org/snippets/679/> .

  • ajax
  • upload
  • progress
Read More

MultiFileWidget

This is a multi file upload widget. That does not require adding multiple file input fields. It requires jQuery.MultiUpload (http://www.fyneworks.com/jquery/multiple-file-upload/)

  • newforms
  • upload
  • multi-file-upload
  • file
Read More

Create new variables in templates

Sometimes you want to create a temporal variable to store something or do anything you want with it, problem is that django template system doesn't provide this kind of feature. This template tag is just for that. Syntax:: {% assign [name] [value] %} This will create a context variable named [name] with a value of [value] [name] can be any identifier and [value] can be anything. If [value] is a callable, it will be called first and the returning result will be assigned to [name]. [value] can even be filtered. Example:: {% assign count 0 %} {% assign str "an string" %} {% assign number 10 %} {% assign list entry.get_related %} {% assign other_str "another"|capfirst %} {% ifequal count 0 %} ... {% endifequal %} {% ifequal str "an string" %} ... {% endifequal %} {% if list %} {% for item in list %} ... {% endfor %} {% endif %}

  • template
  • variable
  • assign
Read More

User post_save signal to auto create 'admin' profile

**How to use:** 1. puts this code at the end of the `models.py` file who haves the User Profile class declared; 2. verify if your User Profile class has the name 'UserProfile'. If not, change the code to the right name. **About:** this snippet makes the ORM create a profile each time an user is created (or updated, if the user profile lost), including 'admin' user.

  • admin
  • user
  • userprofile
Read More