Login

Most bookmarked snippets

Snippet List

RestView - class for creating a view that dispatches based on request.method

Sometimes it's useful to dispatch to a different view method based on request.method - e.g. when building RESTful APIs where GET, PUT and DELETE all use different code paths. RestView is an extremely simple class-based generic view which (although it's a stretch to even call it that) which provides a simple mechanism for dividing up view logic based on the HTTP method.

  • rest
  • view
  • classbasedgenericviews
Read More

Simple Exception Response for AJAX debugging

When debugging AJAX with Firebug, if a response is 500, it is a pain to have to view the entire source of the pretty exception page. This is a simple middleware that just returns the exception without any markup. You can add this anywhere in your python path and then put it in you settings file. It will only unprettify your exceptions when there is a XMLHttpRequest header. Tested in FF2 with the YUI XHR. Comments welcome. EDIT: I recently changed the request checking to use the is_ajax() method. This gives you access to these simple exceptions for get requests as well (even though you could just point your browser there).

  • middleware
  • ajax
  • exception-handling
Read More

An XML-RPC Decorator

Drop this package wherever you want, import the decorator, and use it with one argument to decorate any function you want (`@xmlrpc('pingback.ping')`). That function is now available on your XML-RPC interface, available through this view. Make sure to provide the view (`call_xmlrpc`) with a URL so that it's accessible.

  • xml-rpc
Read More

Sort Table Headers

Handles creation of `order_by` criteria based on GET parameters and provides context variables to be used when generating table header sort links which respect the current sort field and direction, reversing the direction when the same header is sorted by again. Sample view: from somewhere import SortHeaders from django.contrib.auth.models import User from django.shortcuts import render_to_response LIST_HEADERS = ( ('Username', 'username'), ('First Name', 'first_name'), ('Last Name', 'last_name'), ('Email', None), ) def user_list(request): sort_headers = SortHeaders(request, LIST_HEADERS) users = User.objects.order_by(sort_headers.get_order_by()) return render_to_response('users/user_list.html', { 'users': users, 'headers': list(sort_headers.headers()), }) Sample template: {% load my_tags %} <table cellspacing="0"> <thead> <tr> {% table_header headers %} </tr> </thead> <tbody> {% for user in users %}<tr class="{% cycle odd,even %}"> <td><a href="{{ user.get_absolute_url|escape }}">{{ user.username|escape }}</a></td> <td>{{ user.first_name|escape }}</td> <td>{{ user.last_name|escape }}</td> <td>{{ user.email|escape }}</td> </tr> {% endfor %} </tbody> </table> Sample inclusion tag: from django import template def table_header(context, headers): return { 'headers': headers, } register = template.Library() register.inclusion_tag('table_header.html', takes_context=True)(table_header) Sample inclusion tag template: {% for header in headers %}<th{{ header.class_attr }}> {% if header.sortable %}<a href="{{ header.url|escape }}">{% endif %} {{ header.text }} {% if header.sortable %}</a>{% endif %} </th>{% endfor %}

  • sort
  • table
  • headers
Read More

Admin Image Widget

A FileField Widget that displays an image instead of a file path if the current file is an image. Could also be used with sorl.thumbnail to generate thumbnail images. **Example** class FileUploadForm(forms.ModelForm): upload = forms.FileField(widget=AdminThumbnailWidget) class Meta: model = FileUpload class FileUploadAdmin(admin.ModelAdmin): form = FileUploadForm admin.site.register(FileUpload, FileUploadAdmin)

  • image
  • newforms-admin
  • widget
  • file
  • nfa
Read More

Google Geocode Lookup

Makes a call to Google's geocoder and returns the latitude and longitude as a string or returns an empty string. Called by the save method to save the lat and long to the db to be used when rendering maps on the frontend. Reduces the number of calls to geocoder by calling only when saving, not on every viewing of the object. Be sure to import *urllib* and the project's *settings*, and to define GOOGLE_API_KEY in settings.py. **Example:** def save(self): location = "%s+%s+%s+%s" % (self.address, self.city, self.state, self.zip_code) self.lat_long = get_lat_long(location) if not self.lat_long: location = "%s+%s+%s" % (self.city, self.state, self.zip_code) self.lat_long = get_lat_long(location) super(Foo, self).save()

  • google-maps
  • geocode
  • google-api
  • latitude
  • longitude
Read More

Sphinx Search ORM

An ORM model for the Sphinx full-text search engine. See http://www.sphinxsearch.com/ for more information. It currently supports the following: class MyModel(models.Model): search = SphinxSearch() MyModel.search.query('query') MyModel.search.query('query').order_by('@weight', '@id', 'my_attribute') MyModel.search.query('query').filter(my_attribute=5) MyModel.search.query('query').filter(my_other_attribute=[5, 3,4]) MyModel.search.query('query').exclude(my_attribute=5)[0:10] MyModel.search.query('query').count() SphinxSearch().query('hello').on_index('model_myapp model_myotherapp') Returns an ordered list of the objects in your database. -- Update: New Methods: * count() * index_on(<str index>) * extra(<see django>) * all() (does nothing) * select_related(<see django>) * group_by(<str attribute>, <const function>[, <str sort>) * weights(<list weights>)

  • search
  • sphinx
  • full-text
Read More

Dynamically adding forms to a formset with jQuery

I recently worked on an application, where I had to provide a way for users to search for objects based on user-defined properties attached to these objects. I decided to model the search form using a formset, and I thought it'd be a good idea to allow users dynamically add and remove search criteria. The script (dynamic-formset.js) should be re-usable as-is: 1. Include it in your template (don't forget to include jquery.js first!). 2. Apply the 'dynamic-form' class to the container for each form instance (in this example, the 'tr'). 3. Handle the 'click' event for your `add` and `delete` buttons. Call the `addForm` and `deleteForm` functions respectively, passing each function a reference to the button raising the event, and the formset prefix. That's about it. In your view, you can instantiate the formset, and access your forms as usual.

  • newforms
  • jquery
  • dynamic-formset
Read More

Upload progress handler using cache framework

Ticket [#2070](http://code.djangoproject.com/ticket/2070) allows you to create your own file upload handlers. Here's an example handler that tracks a file's upload so you might display a progress meter after form submission. The snippet has two parts, the upload handler which tracks progress, and an upload_progress view used to report back to the browser. The upload handler uses [django's cache framework](http://www.djangoproject.com/documentation/cache/#the-low-level-cache-api) to store the data, which can then be retrieved by the view to send back to the browser. Note: Your form's http post request must have a query parameter (X-Progress-ID) sent along with it, which should contain a unique key to identify the upload. That key will also be sent with your ajax requests to the upload_progress view to retrieve the progress data. Setup: place the UploadProgressCachedHandler anywhere you like on the python path, and add to your settings.py: from django.conf import global_settings FILE_UPLOAD_HANDLERS = ('path.to.UploadProgressCachedHandler', ) + \ global_settings.FILE_UPLOAD_HANDLERS Set up the upload_progress view in any of your apps along with a corresponding entry in your urlconf. Here's some javascript example code to make the ajax requests and display the progress meter: <http://www.djangosnippets.org/snippets/679/> .

  • ajax
  • upload
  • progress
Read More

Getting dynamic model choices in newforms

This is an excerpt from the form code used on this site; the tricky bit here is making the `choices` for the `language` field get filled in dynamically from `Language.objects.all()` on each form instantiation, so that new languages can be picked up automatically. It also adds a blank choice at the beginning so that users can't accidentally ignore the field and incorrectly end up with whatever Language was first in the list. If you use this, always remember that you have to call the superclass `__init__` _before_ you set your dynamic choices, and that you need to accept `*args` and `**kwargs` so you can pass them to it. In theory, `ModelChoiceField` will solve this, but it still seems to be a bit buggy.

  • newforms
  • models
Read More

render_to_response wrapper

Simplifies using RequestContext in render_to_response. Simply call the wrapper with request as the first argument, and the rest of the arguments are as normal for render_to_response. ex: render_response(request, 'foo_list.html', {'foo': Foo.objects.all()})

  • render_to_response
  • requestcontext
  • shortcut
  • template
Read More

Middleware to detect visitors who arrived from a search engine

Sometimes it's nice to know if your visitors came from a search engine such as Google or Yahoo. I use this as a component in determining the popularity of blog articles for search keywords, so I know which articles to automatically feature or suggest. Maybe you'd like to use it to highlight the visitor's search terms on the page. This isn't actually middleware in the sense that it defines any of the middleware interfaces. It's intended to be the base for a middleware method that you write, depending on what you want to happen when you detect that the visitor came from a search engine. In the example `process_view` method, I detect when the request is going to use the `object_detail` view and log the search query for that object in the database.

  • middleware
  • search-engine
  • referrer
Read More

Mini issue tracker

Described more fully on [my blog](http://e-scribe.com/news/230), but the gist is: this model becomes a sort of mini-app in your admin, allowing you to record and track issues related to your other applications. Sorting still needs some work. UPDATED 2007-03-14: Fixed repeat in Admin.list_display (thanks, burly!); added Admin.list_filter; changed app list (why did I call that `PROJECTS`, anyway?) to omit "django.*" apps

  • admin
  • model
Read More
Author: pbx
  • 15
  • 31

Django Paypal

This is a snippet to use Paypal with python. This modifies Mike Atlas's geocept Paypal library. (Which was not working, for me at least) and adds recurring payments. I would try to write an article explaining how to use this and update the snippet.

  • paypal
  • payments
  • payment-processors
Read More

Add delete buttons to admin changelist

This adds a checkbox for each object and three buttons to a model's change list: 1. **Delete selected:** deletes the selected objects 2. **Delete shown: ** deletes all the visible objects. For example, if you perform a search or in any way filter the list, this button deletes only objects that were filtered. 3. **Delete all: ** Deletes all instances of the model, including those not shown (if looking at a filtered list). The deletes perform no confirmation -- once you hit the buttons the models are **gone**, so maybe don't use (or add a confirmation screen) for really sensitive stuff. * uses django oldforms-admin (ie 0.96) * works fine if you include a search_fields list in the Admin class * code for the view could probably be refactored a bit :)

  • admin
Read More

3109 snippets posted so far.