Login

Top-rated snippets

Snippet List

Tuned IPAddressField with IPv4 & IPv6 support using Postgres Network Field type

I wanted to store ipv4 and ipv6 ip's in django but I wanted to use the postgresql inet network field type: http://www.postgresql.org/docs/8.3/static/datatype-net-types.html and I wanted to use IPy.py IP objects in python. I followed these very helpful examples along with the django documentation: http://vaig.be/2009/03/numeric-ip-field-for-django.html http://www.djangosnippets.org/snippets/1381/ It took me awhile to figure out how this works (not that I completely understand it now..) and figured I would share it. If anyone finds problems with this or can make it better I will definitely use it.

  • model
  • field
  • ip
  • custom
  • ip-address
  • ip-addresses
  • ipv4
  • ipv6
  • ipy
  • postgresql-network-field
Read More

ABN and ACN Form Fields

ACNField - Australian Company Number Form Field ABNField - Australian Business Number Form Field Any feedback / Improvements Appreciated.

  • fields
  • forms
  • abn
  • acn
Read More

mini_render_to_response

You need the mini-detector middleware installed [http://www.iterasi.net/openviewer.aspx?sqrlitid=-e2dfig9w0yrclxaigp-uw](http://www.iterasi.net/openviewer.aspx?sqrlitid=-e2dfig9w0yrclxaigp-uw). This is a drop in replacement to render_to_response. When using mini_render_to_response it will try to load a version of your template with mini at the end. For example "home_mini.html" instead of "home.html". If it doesn't find the _mini version it falls back to the regular "home.html" version of your template. Easy way to maintain a "small screen" version of your templates for iPhone or other small screen devices.

  • templates
  • render
  • iphone
  • mini
Read More

highlight pattern

Encloses all matches of a pattern between the opentag and closetag string. ` {% with "this is a large test" as a %} {{ a|highlightpattern:"a" }} {% endwith %} ` yields this is <b>a</b> l<b>a</b>rge test

  • filter
  • highlight
  • pattern
Read More

Widget for Money values on Geraldo Reports

This is a widget for decimal/money/currency fields on **Geraldo Reports**. When you use Geraldo to write reports, decimal fields must be formatted using **get_value** lambda attribute, because ObjectValue doesn't know what mask you want to use. With this widget, you just copy it into a common use Python file, import into your reports file and use it replacing ObjectValue on elements for fields you must be formatted as money format. **Example:** from geraldo import Report, ReportBand, ObjectValue from utils.reports import DecimalObjectValue class ReportCustomers(Report): title = u'Customers List' page_size = A4 class band_detail(ReportBand): height = 0.5*cm elements = [ ObjectValue(attribute_name='id', top=0.1*cm), DecimalObjectValue(attribute_name='salary', left=26.2*cm, top=0.1*cm, format='%0.03f'), ]

  • geraldo
Read More

Widget for DateTime values on Geraldo Reports

This is a widget for date/time fields on **Geraldo Reports**. When you use Geraldo to write reports, date/time fields must be formatted using **get_value** lambda attribute, because ObjectValue doesn't know what mask you want to use. With this widget, you just copy it into a common use Python file, import into your reports file and use it replacing ObjectValue on elements for fields you must be formatted as date/time format. **Example:** from geraldo import Report, ReportBand, ObjectValue, landscape from utils.reports import DateTimeObjectValue class ReportPhoneList(Report): title = u'Phone List' page_size = landscape(A4) class band_detail(ReportBand): height = 0.5*cm elements = [ ObjectValue(attribute_name='id', top=0.1*cm), DateTimeObjectValue(attribute_name='birth_date', left=26.2*cm, top=0.1*cm, format='%m/%d/%Y'), ]

  • geraldo
Read More

Soft hyphenation (&shy;) template filter using PyHyphen

This template filter is meant to insert soft hyphens ([&shy; entities](http://www.cs.tut.fi/~jkorpela/shy.html)) in text whever it can. For this is relies on a **recent** checkout of the [PyHyphen](http://code.google.com/p/pyhyphen/) interface to the hyphen-2.3 C library, which is also used by Mozilla and OpenOffice.org. It takes two optional parameters: the language to hyphenate in and the minimum word length to consider for hyphenation. If no language is given, the default language from the settings file is used. The second parameter defaults to 5 characters. Usage example: {% load hyphenation %} {{ object.text|hyphenate:"nl-nl,6" }}

  • template
  • filter
  • text
  • hyphenation
  • hyphen
  • soft
  • &shy;
  • pyhyphen
  • typografy
Read More

url extension mechanism

Executive summary: url "include" on steroids--granular extra parms and validate names in passing We maintain multiple Django applications, and we use the excellent built-in include mechanism to allow one urls.py to borrow from another: http://docs.djangoproject.com/en/dev/topics/http/urls/ If you scroll down to the section entitled "Passing extra options to include," you will see this annoying limitation: ''' Note that extra options will always be passed to every line in the included URLconf, regardless of whether the line's view actually accepts those options as valid. For this reason, this technique is only useful if you're certain that every view in the included URLconf accepts the extra options you're passing. ''' My snippet overcomes this limitation, allowing you to extend individual urls without polluting the namespace. The function also has the nice side effect of validating that the parent hasn't changed names on you.

  • url
  • extend
  • include
Read More

ThumbnailMixIn

Example mixin for creating and removing thumbnails on a model. Also adds some methods for accessing an url for an image size. It might be a better idea to use a custom image field instead of this approach. Idea for getting the image url for different sizes from http://code.google.com/p/django-photologue Example usage <pre> >>> p.get_small_image_url() u'http://127.0.0.1:8000/site_media/photos/small_someimage.jpg' </pre>

  • image
  • thumbnail
  • model
  • mixin
Read More

Mobilize your Django site

**Mobilize your Django site** This is the code for a Django middleware class to allow you to easily mobilize your Django site. It makes use of [Wapple.net](http://wapple.net)'s Web services to provide device profiling and markup generation. Using this middleware plugin, you can deliver your site to both mobile and web browsers using the same domain and exactly the same url structure and Python views. The WAPL markup language allows you to render sites to every single mobile device without worrying about the individual devices yourself. **Requirements** 1. The [SUDS](https://fedorahosted.org/suds/) Python SOAP client. 2. A WAPL dev key. Sign up for one at [http://wapl.info](http://wapl.info) 3. The Django sessions framework must be enabled. See [http://docs.djangoproject.com/en/dev/topics/http/sessions/](http://docs.djangoproject.com/en/dev/topics/http/sessions/) for how to install. **How To Use** 1. Save the code above as 'wapl_middleware.py' in the root of your project. 2. Replace 'YOUR-DEV-KEY-HERE' with your WAPL dev key. 3. In your project's 'settings'py', add the following to the bottom of your 'MIDDLEWARE_CLASSES' setting: `'myapp.wapl_middleware.WAPLMiddleware',` 4. For each line in your 'TEMPLATE_DIRS' setting, create a new folder under that folder called 'wapl' e.g. for 'myapp/templates/', you would create the folder under 'myapp/templates/wapl/'. 5. For each template used in your application, write a WAPL version and save it in the corresponding 'wapl' directory. See [http://wapl.info/docs/chapter/Developing-with-WAPL/](the WAPL docs) for information about the WAPL markup language. 6. Django template inheritance and includes can be used as normal, so I recommend creating a 'base.html' like this one. `<?xml version="1.0" encoding="UTF-8" ?> <wapl xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://wapl.wapple.net/wapl.xsd"> <head> {% block wapl_head %}{% endblock %} </head> <layout> {% block wapl_layout %}{% endblock %} </layout> </wapl>` 7. View your site from a mobile device, and you should see a nice mobile version. **How It Works** 1. When a request is made, the middleware checks to see if a session variable is held telling us if the device is mobile or not. 2. If we don't already know, it calls the WAPL web services to check. It then stores this in the session for subsequent requests. 3. If the device is a mobile device, it appends 'wapl' to each line in your 'TEMPLATE_DIRS' setting. Your view code will work exactly the same as normal, and the 'wapl' templates will be used whenever a response is rendered. 4. When a response is about to be rendered, the middleware checks to see if the device is a mobile one. 5. If it is mobile, and the response about to be sent has a status code of 200 (OK), it sends the WAPL markup to the WAPL web service to generate the correct markup for that device. 6. Otherwise, it outputs the response unmodified. **Tips** 1. Don't try to migrate your whole site to mobile - design for mobile and consider the user's goals on a handset. 2. If leaving sections out, don't just leave the wapl view out. Include one that says 'This page is not available on mobile'. This will make sure none of your external links are dead on the mobile version. 3. For full developer reference, information and schemas, see [http://wapl.info](WAPL.info).

  • mobile
  • web-services
  • mobilize
Read More

JSON decode datetime

If you have JSON objects with `datetime` attributes that you want to decode to python [datetime](http://docs.python.org/library/datetime.html#datetime.datetime) objects, you can use `decode_datetime` as a [simplejson](http://simplejson.googlecode.com/svn/tags/simplejson-2.0.9/docs/index.html) object hook. `simplejson.loads(s, object_hook=decode_datetime)`.

  • datetime
  • json
Read More

JSON encode ISO UTC datetime

If you want to do your own JSON serialization of [datetime](http://docs.python.org/library/datetime.html#datetime.datetime) objects instead of using DjangoJSONEncoder, use `simplejson.dumps(o, default=encode_datetime)`. The `encode_datetime` method will convert the datetime object to UTC and output an ISO format string just like the [isoutc template filter](http://www.djangosnippets.org/snippets/1424/).

  • datetime
  • json
  • utc
Read More

HTML/JS template filter to show localized dates/times

While working on my website projects today I had the idea to use HTML/JS instead of a IP database to localize the dates and times shown on the websites. Here are the snippets to use the JS snippets as filters for Django running on Google App Engine. You can use those filters on datetime objects.

  • template
  • filter
  • django
  • datetime
  • date
  • time
  • appengine
  • local
Read More

Deli.cio.us rss template tag

This snipped get the latest rss links from delicious from a DELICIOUS_USER that you have to define in your settings. I use this snippet in the [trespams code blog](http://trespams.com) to inform the visitor about the last links I have bookmarked. This is a modified version of [snipped 819](http://www.djangosnippets.org/snippets/819/) to allow using any variable in the template to obtain the results. It also added a 6 hours caché for the rss.

  • delicious
Read More

timeto template filter

This is a more compact version of django's [timeuntil](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#timeuntil) filter that only shows hours & minutes. If used like `{{ dt|timeto }}`, will produce output like "1hr 30min". If you know for sure that the server has the same timezone as the [datetime](http://docs.python.org/library/datetime.html#datetime-objects) value, then you don't need [datetutil.tz](http://labix.org/python-dateutil#head-587bd3efc48f897f55c179abc520a34330ee0a62) for utc time conversion.

  • datetime
  • time
  • humanize
Read More

3110 snippets posted so far.