Login

All snippets

Snippet List

Models for Postal Addresses

Here's some fairly normalized models for representing postal addresses. Making postal_code a separate model would probably be the only way to get it to a level that everyone would agree is 2NF, but we handle a lot of international addresses so that isn't really feasible. Country and StateProvince are intended to be populated with data from ISO 3166. I'd include the SQL I used with that data, but it's very long and there's no attach feature. Also, I'd probably be violating ISO's copyright.

  • models
  • countries
Read More

Excel Spreadsheet Export

This is an example of a view that returns an Excel spreadsheet; the last ~7 lines are the relevant ones. It relies on Excel's ability to automatically import HTML (see http://support.microsoft.com/kb/165499 for more info). The spreadsheet.html template is just has one big `<table>` tag with all the data as table cells (no `<html>` or other surrounding tags are necessary).

  • export
Read More

Gzip decorator

Rather than using the full GZipMiddleware, you may want to just compress some views. This decorator lets you do that. @gzip_compress def your_view(request, ...): ....

  • middleware
  • decorator
  • gzip
Read More

PermanentRedirectMiddleware

This is a simple middleware that redirects the exactly URL requested with the correct domain. It is useful when you have more than one domain (most of cases with "www." or IP) to access a website. To make it works, download the snippet file as the name "permanent_redirect.py" and add its path as the first item in MIDDLEWARE_CLASSES setting in settings.py. Later you must inform a setting called `HTTP_HOST_DOMAIN` with the correct domain.

  • middleware
  • redirect
  • permanent
  • seo
Read More

PostGIS "nearest" including range limiting

this is an enhancement to paulsmith's code snippet 190, to provide an extra "search by distance" parameter rather than "limit number of results returned". i need this for a social networking site where users can search for people within a certain geographical area.

  • postgis
Read More

Credit Card With Newforms

Alternative version of newform code for handling credit cards. Unlike the other two credit-card snippets (http://www.djangosnippets.org/snippets/764/ and http://www.djangosnippets.org/snippets/830/), this uses two drop-down boxes instead of text fields for the expiration date, which is a bit friendlier. It doesn't do as much checking as snippet #764 since we rely on the payment gateway for doing that. We only accept Mastercard, Visa, and American Express, so the validation code checks for that.

  • newforms
  • datefield
  • credit-card
  • expiration-date
Read More

Caching XHTML render_to_response

This code improves on Django's render_to_response shortcut function in the following ways: 1. If the caller does not provide a MIME type, and the caller is passing a RequestContext, it interrogates the request to determine if the HTTP client supports application/xhtml+xml encoding. If so, it sets the request type to application/xhtml+xml to override the HttpRequest class's default mime type of text/html. 2. It caches parsed templates in its own cache to improve performance. If you aren't using XHTML in your templates, you may choose to comment out the code that tests for and sets the application/xhtml+xml MIME type. I place this code in a file named "util.py" in my application. In my views, I write "from app.util import render_to_response" where I used to write "from django.shortcuts import render_to_response". Note that the caching functionality provided by this code means that you will need to recycle your Django instance when you make template changes. Instructions for doing this depend on how you have deployed your Django application.

  • render_to_response
  • template
  • cache
  • html
  • xhtml
Read More

Creator/updater fields for admin

This ModelAdmin class sets fields for models saved in admin corresponding to the user that created the object and the user that last updated the object. Trivial for the current model, but a little more involved to make it work with inlines. The fields still show up as drop-downs (`select`) in the admin, but I fixed that with a little jQuery: $(function(){ $("select[id*='creator'], select[id*='updater']").each(function(){ var user = $('option:selected', this).text(); $(this).siblings('.add-another').hide(); $(this).hide(); $(this).after(user); }); }); This could easily be subverted, but with trusted users, it makes for a quick and dirty read-only field.

  • admin
  • newforms-admin
Read More

Ordering a queryset by _CHOICES

I recently needed to sort a list of objects by cardinal direction clock-wise. Since this is different than alphabetical, and I didn't want to use a dictionary to map to integers, here is what I came up with. There may be a cleaner way to do this by overriding some object methods, but I just thought I'd put this out there anyway.

  • choices
  • ordering
Read More

Authentication Against Active Directory (LDAP) over SSL

I had some trouble getting other peoples code to work for AD support, so I wrote my own which authenticates against LDAP and will also use SSL and cert if required. It will also verify that an autheticated user has specific group membership before authorizing. This will also debug to a file, which is really helpful when trying to figure out problems. One thing that really got me when getting python-ldap to work was that you must have "ldap.set_option(ldap.OPT_REFERRALS,0)" set or any ldap search will not work. Also, this will add group permissions to a user.

  • authentication
  • ssl
  • ldap
  • active-directory
Read More

Custom color field with Javascript color picker

A custom model field 'ColorField' which stores a hex color value like '#FFFFFF' and shows a Javascript color picker in the admin rather than a raw text field. It is written to work with the current trunk (i.e. after newforms-admin merge). You'll need the ColorPicker2.js file found at [www.mattkruse.com](http://www.mattkruse.com/javascript/colorpicker/combined_compact_source.html) (his license prohibits including the file here). This should be placed in the 'js' folder of your admin media. The snippet includes a python source file which can be placed wherever you wish, and a template which by default should be placed in a folder 'widget' somewhere on your template path. You can put it elsewhere, just update the path ColorWidget.render The custom field at present does not validate that the text is a valid hex color value, that'd be a nice addition.

  • newforms
  • javascript
  • models
  • admin
Read More

newforms-admin done the old way

If you view Django's admin pages as a convenience for experts, and so don't see the point in heavily modifying it beyond a few simple things like list_display and some ordering or filtering options, you may feel that newforms-admin makes things harder, not easier. ... Well, there's some truth to that, but it turns out that fighting newforms-admin is doomed - too much has changed to make the fight to preserve the old simplicity winnable to any useful extent, so I'm withdrawing this.

  • newforms-admin
Read More

Admin definition converter (for newforms-admin)

A script I wrote a little while ago to help speed up newforms-admin conversion. From memory it works best when run from an old-forms installation, but it is still useful post-conversion. There are some features missing, but it's supposed to be a starter. Just install this command and run: ./manange.py port2nfa > admin.py (To install, copy the file to management/commands/port2nfa.py in an app somewhere)

  • newforms
  • admin
  • command
Read More

3109 snippets posted so far.