Login

Most bookmarked snippets

Snippet List

Generic CSV Export

This will generically add csv exporting to your views in the admin. It will default to exporting the entire table you see (without paging). If the table only has one column, it will export the fields the the model. You can overide this functionality. I ended up creating my own admin/change_list.html to apply this functionality universally: {% extends "admin/base_site.html" %} {% load adminmedia admin_list i18n %} {% block stylesheet %}{% admin_media_prefix %}css/changelists.css{% endblock %} {% block bodyclass %}change-list{% endblock %} {% if not is_popup %}{% block breadcrumbs %}<div class="breadcrumbs"><a href="../../">{% trans "Home" %}</a> &rsaquo; {{ cl.opts.verbose_name_plural|capfirst|escape }}</div>{% endblock %}{% endif %} {% block coltype %}flex{% endblock %} {% block content %} <div id="content-main"> {% block object-tools %} <ul class="object-tools"> <li><a href="csv/{%if request.GET%}?{{request.GET.urlencode}}{%endif%}" class="addlink">Export to CSV</a></li> {% if has_add_permission %} <li><a href="add/{% if is_popup %}?_popup=1{% endif %}" class="addlink">{% blocktrans with cl.opts.verbose_name|escape as name %}Add {{ name }}{% endblocktrans %}</a></li> {% endif %} </ul> {% endblock %} <div class="module{% if cl.has_filters %} filtered{% endif %}" id="changelist"> {% block search %}{% search_form cl %}{% endblock %} {% block date_hierarchy %}{% date_hierarchy cl %}{% endblock %} {% block filters %}{% filters cl %}{% endblock %} {% block result_list %}{% result_list cl %}{% endblock %} {% block pagination %}{% pagination cl %}{% endblock %} </div> </div> {% endblock %}

  • admin
  • export
  • csv
Read More

Fire Eagle example: views.py from wikinear.com

The views.py used by [wikinear.com](http://wikinear.com/) - see [http://simonwillison.net/2008/Mar/22/wikinear/](http://simonwillison.net/2008/Mar/22/wikinear/) For a more comprehensive API wrapper for Fire Eagle, take a look at [fireeagle_api.py](http://github.com/SteveMarshall/fire-eagle-python-binding/tree/master/fireeagle_api.py)

  • location
  • fireeagle
  • oauth
Read More

Group results by a range of values in admin sidebar

Adds filtering by ranges of values in the admin filter sidebar. This allows rows in numerical fields to be grouped together (in this case, group by price): By store price All < 100 100 - 200 200 - 500 500 - 2000 >= 200 **To use:** 1. save the code as rangevaluesfilterspec.py in your app's directory 2. add `import rangevaluesfilterspec` to your models.py 3. add `myfield.list_filter_range = [value1, value2, ...]` to your filter field **Example:** from django.db import models import rangevaluesfilterspec class Product(models.Model): store_price = models.DecimalField(max_digits=10, decimal_places=2) store_price.list_filter_range = [100, 200, 500, 2000] class Admin: list_filter = ['store_price'] Note that two extra groups are added: less-than the lowest value, and greater-than-or-equal-to the highest value.

  • filter
  • admin
  • sidebar
Read More

Cached Del.icio.us API Calls

This will save your del.icio.us bookmarks in your own database with a Bookmarks model. It depends on several things: 1. `DELICIOUS_USER` and `DELICIOUS_PASS` defined in settings.py 2. [pydelicious](http://code.google.com/p/pydelicious/) installed 3. Any view that uses del.icio.us should call the delicious() function, to update the database. 4. The [cache_function](http://www.djangosnippets.org/snippets/109/) decorator must be available. (I have it in a decorators.py file in my app; if you move it, you need to update the import) 5. The [django-tagging](http://code.google.com/p/django-tagging/) app, although it could be modified to not need this rather easily. Other than all those dependencies, it's actually rather simple. It will call del.icio.us for the 5 most recent posts, and create them if they're not already in the database. Otherwise, it'll check for updates, and change as appropriate. It won't return anything, as it updates the models themselves.

  • cache
  • delicious
  • pydelicious
  • api
  • bookmarks
Read More

Cache Any Function

A decorator similar to `cache_page`, which will cache any function for any amount of time using the Django cache API. I use this to cache API calls to remote services like Flickr in my view, to prevent having to hit their servers on every request. I posted a sample function which uses the [delicious API](http://www.djangosnippets.org/snippets/110/) in the function, also. **Update**: It now also will put in a temporary 'in-process' variable (an instance of `MethodNotFinishedError`) in the cache while the function is processing. This will prevent the cache from calling the method again if it's still processing. This does not affect anything **unless you're using threads**.

  • cache
  • function
  • threading
  • threads
  • thread
Read More

Render specific blocks from templates (useful for AJAX, alternative)

Special thanks to the author of snippet 769 who provided most of the code for this snippet. Major differences: 1.Simpler/better handling of "extends" block tag 2.Searches If/Else blocks 3.Less code 4.Allow list of templates to be passed which is closer to the behavior of render_to_response

  • template
  • block
  • templates
  • render
  • context
  • blocks
Read More

render_to

Decorator, written for views simplification. Will render dict, returned by view, as context for template, using RequestContext. Additionally you can override template, returning two-tuple (context's dict and template name) instead of just dict. Usage: @render_to('my/template.html') def my_view(request, param): if param == 'something': return {'data': 'some_data'} else: return {'data': 'some_other_data'}, 'another/template.html'

  • render_to_response
  • requestcontext
  • shortcut
  • decorator
  • rendering
Read More

Plugin Framework

This is a very basic -- yet fully functional -- framework for producing a loosely coupled plugin architecture. Full details of its use can be found [on my blog](http://gulopine.gamemusic.org/2008/jan/10/simple-plugin-framework/), but the basics are listed below. ## Defining a mount point for plugins class ActionProvider: __metaclass__ = PluginMount ## Implementing plugins class Insert(ActionProvider): def perform(self): # Do stuff here class Update(ActionProvider): def perform(self): # Do stuff here ## Utilizing plugins for action in ActionProvider.plugins: action.perform() Yes, it really is that simple.

  • plugins
Read More

Debug Page Load Time Stats Middleware

Use this to display a split of page execution time between python and the db in your base template when debugging. I originally got the base of this code from another snippet, but I can't find it anymore and want to share with new folks because I find this handy.

  • middleware
  • profile
  • time
  • debug
  • performance
  • query
  • basetemplate
Read More

SQL Printing Middleware

Just put it in your python path and add it into MIDDLEWARE_CLASSES. I know that there are a couple of snippets on this site that do something similar to this, but none of them quite suited me. I wanted something that would indent and space the SQL so that I could differentiate it from the other output from the development server. Also, I wanted something that would output total query execution time, which my solution does. I just hope that it's useful for someone else, too! UPDATE: Now this should no longer get upset when running it on windows.

  • sql
  • middleware
  • profile
  • debug
  • help
  • console
  • printing
  • speed
Read More

Slightly better media path tag

A slightly improved version of [snippet #195](/snippets/195/) which keeps the logic but makes use of the `simple_tag` decorator to drastically simplify the code. For an alternative to this sort of tag, check out the media context processor in my [template_utils app](http://code.google.com/p/django-template-utils/).

  • template
  • tag
  • media
  • simple_tag
Read More

Database migration and dump/load script

I once needed to convert a Django project from PostgreSQL to SQLite. At that time I was either unaware of manage.py dumpdata/loaddata or it they didn't yet exist. I asked for advice on the #django IRC channel where ubernostrum came up with this plan: simple process: 1) Select everything. 2) Pickle it. 3) Save to file. 4) Read file. 5) Unpickle. 6) Save to db. :) Or something like that. First I thought it was funny, but then started to think about it and it made perfect sense. And so dbpickle.py was born. I've used this script also for migrating schema changes to production databases. For migration you can write plugins to hook on dbpickle.py's object retrieval and saving. This way you can add/remove/rename fields of objects on the fly when loading a dumped database. It's also possible to populate new fields with default values or even values computed based on the object's other properties. A good way to use this is to create a database migration plugin for each schema change and use it with dbpickle.py to migrate the project. See also [original blog posting](http://akaihola.blogspot.com/2006/11/database-conversion-django-style.html) and [my usenet posting](http://groups.google.com/group/django-users/browse_thread/thread/6a4e9781d08ae815/c5c063a288483e07#c5c063a288483e07) wondering about the feasibility of this functionality with manage.py dumpdata/loaddata. See [trac site](http://trac.ambitone.com/ambidjangolib/browser/trunk/dbpickle/dbpickle.py) for version history.

  • dump
  • database
  • migration
  • load
  • pickle
Read More

3110 snippets posted so far.