Login

Snippets by acdha

Snippet List

Reliably create a Django File using the contents of a URL

There's no direct way to save the contents of a URL to a Django File field: you're required to use a File instance but those can only safely wrap normal files, not the file-like object returned by urllib2.urlopen. Several examples online use urllib.urlretrieve() which creates a temporary file but performs no error handling without writing a ton of hackish code. This demonstrates how to create a NamedTemporaryFile, fill it with the URL contents and save it, all using APIs which raise exceptions on errors.

  • url
  • filefield
  • file
  • urlopen
Read More

Encoding datetime for JSON consumers like YUI

Passing datetimes from Python to a [YUI DataTable](http://developer.yahoo.com/yui/datatable/) via JSON served by [django-piston](http://bitbucket.org/jespern/django-piston/) turned out to be surprisingly rocky. This code actually works with ``YAHOO.lang.JSON.stringToDate`` (*not* ``YAHOO.util.DataSource.parseDate``) which cannot handle time zone specifiers other than "Z" or dates without timezones. The YUI [DataSource](http://developer.yahoo.com/yui/datasource/) which uses this looks something like this - note that simply setting ``format:"date"`` does not work as that uses ``YAHOO.util.DataSource.parseDate``, which uses``Date.parse`` to do the actual conversion, which will involve browser-specific formats and as of this writing only Chrome's native ``Date`` can reliably parse ISO 8601 dates. myDataSource.responseSchema = { resultsList: '…', fields: [ … { key: 'my_date_field', parser: YAHOO.lang.JSON.stringToDate }, ], … };

  • javascript
  • date
  • json
  • iso8601
Read More

Private Context Decorator

Django's standard inclusion_tag doesn't include context variables by default. When you add takes_context you are required to manually merge the context variables into the dict which your tag returns, which tends to result in wasteful code or [possibly accidentally] leaking variables into the global context (`context.update({…})`). This decorator allows your inclusion tag to remain simple and still have safe access to the global context for things like `MEDIA_URL`: @register.inclusion_tag('my_template') @private_context def my_tag(context, …): return {"foo": 1, "bar": 2}

  • templatetag
  • decorator
  • context
  • inclusion_tag
Read More

acdha has posted 3 snippets.