Login

Most bookmarked snippets

Snippet List

base class to easily expose json based web services

*JsonWebService.jsonresponse JsonWebService provides the property jsonresponse which marks the method it is applied to, and also serializes to json the response of the method. *JsonWebService.urls Scans the marked methods and build a urlpattern ready to use in urls.py

  • json
  • webservice
Read More

Image model with thumbnail

A relatively simple Photo model which generates its own thumbnail when saved. A default size is specified as `thumb_size` in the `save()` arguments. Other thumbnailing strategies don't save the thumbnail dimensions, and since the actual dimensions of the thumbnail created by PIL's `thumbnail` method are somewhat non-deterministic, it is difficult to create an `img` tag with proper height and width attributes. This approach makes that task simple. This approach works well if only one thumbnail size is required. It could easily be adapted to support two or three thumbnail sizes, but adding more sizes would quickly get unwieldy. This was adapted from http://biohackers.net/wiki/Django1.0/Thumbnail

  • image
  • thumbnails
  • thumbs
Read More

Use JQuery Calendar in ModelForm

The important code really is just setting up the base site to use jquery and then using the javascript function to show the calendar on a widget with the .vDateField class set. The DateField modeltype automatically gets the css class .vDateField when using ModelForms.

  • jquery
  • calendar
  • widget
  • modelform
Read More

In-memory XML-RPC server based on URL

This is a XML-RPC server, that uses arguments in URLs and every dispatcher instance is prepared in memory during webserver run. It's good, for example, for securing XML-RPC server with hashed strings and there are a lot of similar use cases. Usage: from xmlrpclib import ServerProxy server = ServerProxy('http://example.com/xmlr-rpc/%s/' % something, allow_none=True) server.do_something(*args)

  • xml
  • server
  • dispatcher
  • xmlrpc
Read More

Quiet runserver

It's quite common to use Django's `static.serve` functionality to serve media assets via the built-in development server. However, I always find that this is far too noisy - every asset produces a line of output on the console, and any debug messages I want to put there are hard to see. This management command monkey-patches the built-in `runserver` command so that it only generates a line of output for actual Django views - anything else is served as usual, but is not logged to the console. In fact the original version was already doing this for admin media, but not for your own media - I've just extended the logic. Put this in the management/commands directory of an installed app, saving it as (for example) `runserver_quiet`, then just do `./manage.py runserver_quiet` to run - it will accept all the same arguments as the built-in version.

  • runserver
  • management-command
Read More

assertQuerysetEqual

I often find myself testing that the queryset returned by a method contains the instances I expect. I use a custom method, **assertQuerysetEqual()**, to test the equality of two querysets or lists:: def test_some_values(self): qs = get_user_list() self.assertQuerysetEqual(qs, [normal_user, super_user]) Makes it easy to test small querysets against lists whose values are known and expected.

  • testing
  • test
Read More

Dynamically change admin widgets at runtime

django-adminwidgetswap =============== adminwidgetswap is used for dynamically swapping out widgets from django's generated admin. This allows applications to be packaged generically without the need for WYSIWYG dependencies editors- giving the application consumer the freedom to chose admin widgets without modifying original app source. Author ====== [David Davis](http://www.davisd.com) (http://www.davisd.com) [dynamically change django admin widets at runtime (django-adminwidgetswap) blog post](http://www.davisd.com/blog/2010/04/17/dynamically-change-django-admin-widgets-at-runtime/) Usage =============== To change a widget in django's admin, just put adminwidgetswap.py on the python path, import adminwidgetswap.py and use: adminwidgetswap.swap_model_field(model, field, widget) ...to change a widget for a direct model admin's field --- adminwidgetswap.swap_model_inline_field(model, field, widget) ...to change widgets for inlines of a specific model and field --- adminwidgetswap.swap_model_and_inline_fields(model, field, widget) ...to change both the widget for the direct model admin's field as well as all inline usages for the model and field --- I usually have a project-level application called website, and I put this initialization code inside the website app's __init__.py Usage - parameters =============== model is the Model class (eg. models.GalleryImage) field is the field name you're looking to swap (eg. 'image') widget is the widget you're going to swap for (eg. widgetlibrary.ThumbnailWidget())

  • admin
  • widgets
  • abstraction
Read More

plaintext filter

Inspired by this [terse blog post](http://www.ghastlyfop.com/blog/2008/12/strip-html-tags-from-string-python.html). This filter was designed to simplify the stripping out of all (x)html in a given template var, while preserving some meta information from anchor, and image tags. Why is this even useful? If you have pre-assembled portions of templates, or model fields containing html, that you want to use to populate a *search index* like [django-haystack](http://haystacksearch.org/) you can safely discard all the markup, while keeping the text that should be still searchable. Alt text, and title attributes are worth keeping!

  • template
  • filter
  • striptags
Read More

Breaking tests.py into multiple files

Django loads tests found in models.py and tests.py (if present) or actually a module or package named 'tests' under the app. Since tests can be a package, one can create a 'tests' directory, split the test cases across multiple files under 'tests' and import them from tests/__init__.py with: # tests/__init__.py from test_mod1 import * from test_mod2 import * ... from test_modN import * For a small number of files that's not too bad but it gets old as more files are added, plus it is error prone (e.g. test cases shadowing others with the same name). The snippet above simplifies the test splitting without importing everything into the same namespace. Typical usage: # tests/__init__.py from ... import get_suite suite = lambda: get_suite(__name__)

  • testing
  • tests
  • test
Read More

ModelChoiceField with optiongroups

This is a ModelChoiceField where the choices are rendered in optiongroups (this is already posible with a normal Choicefield) For this to work properly the queryset you supply should already be ordered the way you want (i.e. by the group_by_field first, then any sub-ordering) See [related blog article](http://anentropic.wordpress.com/2010/03/23/django-optiongroups-for-your-modelchoice-field/)

  • modelchoicefield
  • optiongroup
Read More

IPAddressField with CIDR support

Based on #1381 Use this piece of code to add IPv4/IPv6 and network support to Django. An IPAddressField allows you to find IP's for a given subnet. An IPNetworkField allows you to find a subnet for a given IP or find a subnet within a subnet. For starters, simply paste it into a new file in your app called fields.py. IPAddressField example # models.py from fields import IPAddressField class IPTest(models.Model): ip = IPAddressField() To search for an IP within a given subnet from ipaddr import IPNetwork IPTest.objects.filter(ip__in=IPNetwork('10.0.0.0/24')) IPNetworkField example # models.py from fields import IPNetworkField, IPNetworkQuerySet class IPTest(models.Model): objects = IPNetworkQuerySet.as_manager() network = IPNetworkField() To search for a subnet with a given IP from ipaddr import IPAddress IPTest.objects.network('network', IPAddress('10.0.0.1'))

  • cidr
  • ipv4
  • ipv6
  • ipaddress
  • ipnetwork
Read More

Multiple emails form field

Field which accepts list of e-mail addresses separated by any character, except those which valid e-mail address can contain.

  • multiple
  • email
  • form
  • field
  • list
Read More

3110 snippets posted so far.