Login

Most bookmarked snippets

Snippet List

Publishing service endpoint uri to javascript

My application is made up of two main pieces: 1) an ajax client, and 2) backend services supplying data to the ajax client. Django delivers html files that bootstrap the javascript client, which in turns calls back to Django's restful services. Most of javascript code is in static .js files that being delivered to the browser bypassing Django. When calling back into Django, I started by embedding call endpoints into the javascript code. Soon, I noticed, though, that every time I adjusted an endpoint's url in urls.py, I also had to remember to go back and adjust the javascript. This was suboptimal and violated the DRY principle. I realized that all the information I needed was already in urls.py. All that needed to be done, was to find a way to expose that information to the javascript environment. The code I'm including does exactly that. It consists of two pieces: a view function and a corresponding javascript template. The view function will go through all declared urls looking for those whose name ends with '-svc'. These urls are then converted into javascript constants by the template. The url names are slightly mangled to conform to javascript identifier conventions and if you have any url parameters, they will be encoded into something that javascript can easily replace with real values at run time. For example, `url('^blog/(?P<id>[\d]+/$', 'sample.views.showblog', name='blog-entry')` will become `svc.__BLOG_ENTRY = "/blog/{id}/"` to get the uri from your javascript code, you simply make this call: `svc('BLOG_ENTRY', {id: 12345})` and you'll get back `/blog/12345/` Requirements: the javascript template assumes availability of the Namespace library by Maxime Bouroumeau-Fuseau (http://code.google.com/p/namespacedotjs/)

  • javascript
  • urls
  • url
  • service
  • endpoint
Read More

Parsing Tag decorator

A simple decorator to register a template.Node object as a tag, without the need to write the usual "`token.split_contents()` yatta yatta blatta blatta" function. The decorator should be called with the name of the tag, and an optional `required` named argument in case your tag requires a minimum number of arguments. Please note that all the arguments in the templatetag call will be passed to the node (except the templatetag name and the `for` and `as` keywords) in the order given. Suggestions etc are very welcome, of course =)

  • templatetag
Read More

Call a manager method on any model with a filter

Often I want to call a custom manager method in the template, something like Snippet.objects.get_latest(). I hate writing custom templatetags to do all that work, so instead I've written a filter that will work for any. Here's how I use it: {% for snippet in "cab.snippet"|call_manager:"top_rated"|slice:":5" %}

  • template-filter
Read More

Cached template filters

Say you'd like to cache one of your template filters. This decorator acts sort of like memoize, caching a result set based on the arguments passed in (which are used as the cache key).

  • template
  • cache
Read More

Admin Save and view next button

Add a Save and view next button to your admin change form. Put the code at [link](http://www.djangosnippets.org/snippets/2006/) in a file called myapp/templates/admin/myapp/change_form.html Note: Requires Django 1.2.

  • admin
  • view
  • save
  • button
  • next
  • 1.2
Read More

Quick script to convert json data to csv

I often need to dump data from a database to csv. This little snippet should make it easy enough to do without having to worry too much about character encodings, though it does assume you want your csv file to be utf-8 encoded. Note that this dumps just one table from the database. Trying to dump all the tables in your app will raise an exception.

  • json
  • csv
  • utility
Read More

Easier prefix handling for forms

**autoprefixed** is a decorator for Form classes that simplifies prefix handling by storing it in a hidden field. Thus when the form is posted, the prefix can be extracted from the posted data instead of having to pass it explicitly when instantiating the form.

  • form
  • prefix
Read More

immitating 'real' post_syncdb signal

I did not like the idea of having to load fixtures by creating a huge initial_data.json file. I also did not want to store my initial data in a bunch of <modelname>.sql files. Django has post_syncdb signal which fires when model(s) for an application are installed, but I needed something that would run only *once* at the end of syncdb command, at least after all of the models are installed, and here's what I've come up with. The code basically checks if the current callback is for the last app in your INSTALLED_APPS, and if so, executes some fixture loading code.

  • signals
  • post_syncdb
Read More

Dictionary of choices based in models

Sometimes we need to build a ChoiceField from data in a Model or more than just one model via fk's but the ModelChoiceField is not *that* flexible. So, in order to obtain a list of tuples with pk and a descriptive text for the choices parameter of the ChoiceField use this little function.

  • forms
  • choicefield
  • zip
  • list-of-tuples
  • orm-and-forms
Read More

Security: Sideband information cover traffic middleware

This is a quick hack to address the SSL info leakage covered here: http://www.freedom-to-tinker.com/blog/felten/side-channel-leaks-web-applications Don't use this in prod without testing. :-) I'll get some feedback from django-dev and update here.

  • middleware
  • ssl
  • security
Read More

FloatField with safe expression parsing

This FloatField replacement allows users to enter math expressions, such as: 4/5 + sqrt(32) And will evaluate them safely when the field's clean() function is called. In the example above, it will evaluate to a float value of about 6.457. Reference: [http://lybniz2.sourceforge.net/safeeval.html](http://lybniz2.sourceforge.net/safeeval.html) The available functions are listed herein. Note that the from __future__ import division causes integer division expressions to be evaluated as floats. For example "1/2" evaluates as 0.5 when it would otherwise have evaluated to 0 (assuming Python 2.X).

  • fields
  • forms
  • parser
  • math
  • eval
  • parsing
  • floatfield
Read More

3110 snippets posted so far.