Login

All snippets written in Python

Snippet List

Manipulate URL query strings using context variables using a template tag

A template tag that includes a modified version of the GET query string. the query string can be manipulated by adding and removing fields. If a value is given that resolves to a context variable that the value of the variable is used. Based on [this snippet by dnordberg](http://djangosnippets.org/snippets/826/), but with the ability to use context and done in a cleaner manner, without the need to add an arbitrary template.

  • url
  • template-tag
  • query-string
Read More

CheckboxSelectMultiple that renders in columns

This is a CheckboxSelectMultiple widget that will render its choices divided evenly into multiple ul elements that can be styled nicely into columns. Pass in a css class to the constructor to be assigned to the ul's. See also: http://code.djangoproject.com/ticket/9230

  • checkbox
  • columns
Read More

GeoDjango maps in admin TabularInlines

This snippet adds support for OSM maps for GeometryField in Admin TabularInlines. The one possible issue with this snippet is that the OSMGeoInlineForm has to know about the parent ModelAdmin which it does through the code `model_admin_instance = admin.sites.site._registry[self.parent_model]` which won't work if you don't use the default model admin to register the model admin. I'll try and come up with a work around and edit the snippet. Due to the need to mess around with inline style sheets and IE not playing ball with just copying the innerHTML I've settled on using the jQuery.Rule plugin which I've included here as the last version published on the site was incompatible with jQuery 1.4.2 and I found a pathced version online, I also had to modify it due to the Django admin using the compatibility mode of jQuery so there is no global jQuery variable it's django.jQuery instead. 1. Create an osmgeo_inline.py file in your app and copy the top code into it. 2. Create the template file in a directory called admin within a template directory for your app, the template file must be called osmgeo_tabular_inline.html, and copy the middle code into it. 3. Create the jquery rule plugin file in your media or admin-media js directory and copy the bottom code into it. Don't forget to change the OSMGeoInlineForm's class Media's js = ('.....',) to the correct path to the file if need be. 4. In your admin.py you can create inline models using OSMGeoTabularInline just as you would TabularInline. Examples all based on the following in models.py from django.contrib.gis.db import models class MyModel(models.Model): name = models.CharField(max_length=64) route = models.LineStringField(srid=settings.WGS_SRID) class MySubModel(models.Model): mymodel = models.ForeignKey(MyModel) name = models.CharField(max_length=64) location = models.PointField(srid=settings.WGS_SRID) Example 1 - basic usage (admin.py): from django.contrib.gis.admin import OSMGeoAdmin from myapp.osmgeo_inline import OSMGeoTabularInline from myapp.models import MyModel, MySubModel class MySubModelInline(OSMGeoTabularInline): model = MySubModel class MyModelAdmin(OSMGeoAdmin): inlines = [MySubModelInline] admin.site.register(MyModel, MyModelAdmin) Example 2 - overriding the default map widget params and setting the inline map's centre point to match the main models map centre (admin.py): from django.contrib.gis.admin import OSMGeoAdmin from myapp.osmgeo_inline import OSMGeoTabularInline from myapp.models import MyModel, MySubModel class MySubModelInline(OSMGeoTabularInline): model = MySubModel class MyModelAdmin(OSMGeoAdmin): inlines = [MySubModelInline] params = {'map_width: 200, 'map_height': 200] def get_formset(self, request, obj=None, **kwargs): centre = None if obj is not None: centre = obj.route.centroid.transform(900913, clone=True) self.params['default_lon'] = centre.coords[0] self.params['default_lat'] = centre.coords[1] self.params['default_zoom'] = 12 return super(TrailSubmissionInlineBase, self).get_formset(request, obj, **kwargs) admin.site.register(MyModel, MyModelAdmin) I've not looked at StackedInlines because I don't use them but all that would be needed is to add a class OSMGeoStackedInline(StackedInline) that was a copy of OSMGeoTabularInline but with a template based on the StackedInline template - the javascript code in var initMap = function(row) would probably have to be adapted though.

  • django
  • admin
  • geodjango
  • map-widget
  • tabular-inlines
Read More

Modify requests in your unit tests (improvement on RequestFactory)

This is an update to Simon Willison's snippet http://djangosnippets.org/snippets/963/, along with one of the comments in that snippet. This class lets you create a Request object that's gone through all the middleware. Suitable for unit testing when you need to modify something on the request directly, or pass in a mock object. (note: see http://labix.org/mocker for details on how to mock requests for testing) Example on how to use: from django.test import TestCase from yourapp import your_view from yourutils import RequestFactory class YourTestClass(TestCase): def setUp(self): pass def tearDown(self): pass # Create your own request, which you can modify, instead of using self.client. def test_your_view(self): # Create your request object rf = RequestFactory() request = rf.get('/your-url-here/') # ... modify the request to your liking ... response = your_view(request) self.assertEqual(response.status_code, 200) Suggestions/improvements are welcome. :)

  • testing
  • request
  • client
  • testcase
Read More

New view decorator to only cache pages for anonymous users

This is an addition to Django's cache_page decorator. I wanted to cache pages for anonymous users but not cache the same page for logged in users. There's middleware to do this at a site-wide level, and it also gives you the ability to partition anonymous users, but then you have to tell Django which pages not to cache with @never_cache.

  • cache
  • view
  • decorator
  • anonymous
Read More

RelatedNullFilterSpec: django-admin custom filter all/null/not null/choices

A simple django-admin filter to replace standar RelatedFilterSpec with one with the "All"/"Null"/"Not null" options. It applies to all relational fields (ForeignKey, ManyToManyField). You can put the code in the `__init__.py` or wherever you want. The `_register_front` idea is copied on [this snippet](http://djangosnippets.org/snippets/1963/)

  • filter
  • admin
  • null
  • filterspec
  • ManyToManyField
  • ForeignKey
  • not-null
Read More

Simple Mobile Support

For those interested in making a mobile site geared toward the higher end devices, and wanting a little leverage over device-specific quirks. These are the big players in the U.S. market, but of course, add your own User-Agents to match your audience's popular browsers. Usage: <html class="{{ device.classes }}"> You can also leverage template logic: {% if device.iphone %} <p>You are browsing on {% if device.iphone = "iphone4" %} iPhone 4 {% else %} an iPhone pre-version 4{% endif %} </p> {% endif %}

  • mobile
  • context_processors
Read More

X-Sendfile static file serve view

This view has the same functionality as Django's builtin static view function but when the configuration option `USE_XSENDFILE = True` is specified in the settings it returns the absolute path of the file instead of its contents. This allows the mod_xsendfile module in Apache or Lighttpd to take care of efficiently serving the file while still allowing for Django to take care of other processing of the request, like access control or counting the amount of downloads.

  • static
  • xsendfile
Read More

Improved command to generate UML diagrams of whole project or specified apps

example of use: 1. python manage.py yuml yourapp yoursecondapp --scruffy -s 75 -o test.png 2. python manage.py yuml justoneapp --scruffy -o test.pdf 3. generate whole project yuml : python manage.py yuml -a -o test.jpg 4. python manage.py yuml auth contenttypes sessions admin -o test.pdf [github repository](http://github.com/dzhibas/django-yuml)

  • django
  • command
  • basecommand
  • uml
  • yuml
Read More

2955 snippets posted so far.