Login

Most bookmarked snippets

Snippet List

Foldable Admin Interface

Have you had a rather huge database, say 50-100+ tables? Why not compress the tables you don't want to see and expand the ones that you do want to see? This template should do the trick. It uses cookies to remember which tabs you have open and which ones you have closed. This should work on .91 to current. How to install - just CP code and save as index.html toss in your media folder under /path_to_media/template_folder/admin/index.html. next download mootools and toss this into /path_to_media/js_folder/mootools.js (alternatively you could be lazy and cp mootools into the script tag of this template) A quick and dirty fix but it sure saves time trying to find the tables you are looking for.

  • django
  • admin
  • templates
  • html
Read More

Decorating urlpatterns

One thing I wanted for a while was the ability to basically apply something like @login_required to a bunch of urlpatterns in one go, instead of having to decorate each and every view manually. In this example, the latter two views will always raise a 404.

  • urls
  • views
  • decorators
  • urlpatterns
Read More

Cache decorator

You can use this cache all your functions' output, except dynamic things like connection.cursor.

  • django
  • cache
  • decorator
Read More
Author: xyb
  • 0
  • 9

nginx x-accel-redirect protection of static files

This snippet requires nginx as your front end server (for serving static files) and any django enabled server as a backend that only gets the dynamic requests (I use apache with mod_python). If you have no idea what I'm talking about, you probably won't need this snippet. I previously tried something [similar](http://www.djangosnippets.org/snippets/62/) just using mod_python, but this was too unstable for my needs (the PythonAuthenHandler seems to be called multiple times for no apparent reason). The patch from that snippet was also used as a base for [this ticket](http://code.djangoproject.com/ticket/3583). This is part of an authentication mechanism I use for protecting static files. Nginx has the so called x-accel-redirect feature, that tells nginx to serve an internal (read 'protected') file if the backend response has the ['X-Accel-Redirect'] header set. No other headers are touched, but by deleting all relevant headers in the default django response, nginx will create those headers for us. The usage is pretty simple: * set up nginx as a proxy for apache + mod_python + django (google for this if you don't know how) * configure nginx as shown in the code snippet (for testing leave out the internal part to see if the files are accessible) * configure your urls.py to point to the validation view * make your sites hrefs point to the view instead of the file directly (those real urls will be completely hidden from your visitors) * Done!

  • authentication
  • nginx
Read More

AutoSlugField

This is a simple solution aimed at saving some time when you simply want to get a slug from a model field just before saving.

  • fields
  • slug
  • field
Read More

FileField / ImageField with a delete checkbox

Example model: class MyModel(models.Model): file = RemovableFileField(upload_to='files', \ null=True, blank=True) image = RemovableImageField(upload_to='images', \ null=True, blank=True) A delete checkbox will be automatically rendered when editing such a model using form_for_instance. [UPDATED version which works with ModelForms](http://www.djangosnippets.org/snippets/636/)

  • newforms
  • models
  • imagefield
  • filefield
  • remove
  • delete
Read More

filter/search a newforms select widget

Adds a filter input above a select widget that allows live-filtering on the client-side (no ajax) in Firefox. Example: make_fields_searchable(ModelItemForm, { 'publisher': {'set_size': 8}, 'developer': {'set_size': 8}, 'genre': {}, 'platform': {} })

  • filter
  • newforms
  • search
  • model
  • widgets
  • select
Read More

Middleware for printing of exception to console

The django debug screens are great, but only when you can see them. Trying to debug javascript/ajax calls can be kind of a pain. This just a copy/paste of some code in django's internals stuck in a middleware so that exceptions also print to the dev server console.

  • middleware
  • console
  • exception
Read More

Code syntax highlighting templatetag

Replaces <code> blocks with syntax highlighted code. Use CSS to actually get the colours you want, look at pygments documentation for extracting css for various styles. This snippet has the advantage of falling back on <pre> if anything goes wrong, and attempting to guess the syntax of code, falling back on python.

  • templatetag
  • pygments
  • highlighting
  • beautifulsoup
  • templatetags
  • syntax
  • syntax-highlightin
Read More

True links in the admin list

Usually, you can add links in the admin using such code: class Pingback(models.Model): #... target_uri = models.URLField( _('Target URI')) #... def admin_target(self): return '<a href="%(targ)s">%(targ)s</a>' % {'targ': self.target_uri} admin_target.short_description = _('Target URI') admin_target.allow_tags = True #... class Admin: list_display = ('id', 'admin_target') But when you have two or more url fields, such approach becomes to expensive. Follow the DRY principe and use my code in such way: # Just add this line instead of the ugly four lines **def blabla** admin_target = link('target_uri', _('Target URI'))

  • admin
Read More

UTC DateTime field

A DateTime field extension that automatically stores the timezone, and the computed UTC equivalent. This field needs the pytz library. The field adds two new fields to the model, with the same name of the UTCDateTimeField field, and a suffix. For an UTCDateTimeField named 'updated', the model will contain * an 'updated' field, which holds the local datetime * an 'updated_utc' field, which holds the corresponding UTC datetime * an 'updated_tz' field, which holds the field timezone name The timezone can vary between model instances, just set the 'xxx_tz' field to the desired timezone before saving. UTCDateTimeField supports a single optional keyword argument 'default_tz', in addition to the DateTimeField standard ones, to let the user choose a provider for a default timezone when no timezone has been set. Its value can be * None (or the argument missing), in which case the default settings.TIME_ZONE will be used * a callable, which will be called when the 'xxx_tz' field is emtpy, which should return a timezone name * a string, which will be used to access a model attribute or call a model method, which should return a timezone name If the timezone name points to a non-existent timezone, a warning will be issued and the default settings.TIME_ZONE value will be used. The field will also add three properties to the model, to access the pytz timezone instance, and the offset aware datetimes for local time and UTC. For the same 'updated' field instance we used above, the three properties added to the model will be: * updated_timezone * updated_offset_aware * updated_utc_offset_aware A brief example on how to use UTCDateTimeField: class UTCDateTimeTest(models.Model): """ >>> import datetime >>> d = datetime.datetime(2007, 8, 24, 16, 46, 34, 762627) # new instance, tz from model method >>> t = UTCDateTimeTest(updated=d) >>> t.save() >>> t.updated datetime.datetime(2007, 8, 24, 16, 46, 34, 762627) >>> t.updated_utc datetime.datetime(2007, 8, 24, 14, 46, 34, 762627) >>> t.updated_tz 'Europe/Rome' >>> t.updated_timezone <DstTzInfo 'Europe/Rome' CET+1:00:00 STD> >>> t.updated_offset_aware datetime.datetime(2007, 8, 24, 16, 46, 34, 762627, tzinfo=<DstTzInfo 'Europe/Rome' CEST+2:00:00 DST>) >>> t.updated_utc_offset_aware datetime.datetime(2007, 8, 24, 14, 46, 34, 762627, tzinfo=<UTC>) >>> """ updated = UTCDateTimeField(default_tz='get_tz') def get_tz(self): return 'Europe/Rome'

  • models
  • fields
  • datetime
  • timezone
  • field
  • utc
Read More

Add parameters to the current url

Often a page contains a link to itself, with an additional parameter for in the url. E.g. to sort the page in a different way, to export the data into another format, etc... This tag makes this easy, avoiding any hardcoded urls in your pages.

  • url
  • parameter
Read More

Sphinx Search ORM / Revised

A revised version of [zeeg's Sphinx Search ORM](http://www.djangosnippets.org/snippets/231/), using my Sphinx client and adding support for Sphinx's excerpt generator. It's still missing support for search modes/order_by/filter/exclude, but it should be easy and I will add the relevant methods soon as I need them. Usage is the same as zeeg's class, except that you can pass a field name (or tuple for related objects) to its constructor, that will be used for excerpts: class MyModel(models.Model): search = SphinxSearch(excerpts_field='description') MyModel.search.query('query') MyModel.search.query('query').count() Returns an ordered list of the objects in your database.

  • search
  • sphinx
  • full-text
Read More

MaxMind(R) GeoIP Lite CSV Import

Use this script to import the Maxmind GeoIP lite CSV datasets into your database. This takes at least 200MB of RAM; the resulting database will be ~400MB. Stick in the same directory as the [models](http://www.djangosnippets.org/snippets/327/). Make sure to set `DEBUG=False` to prevent running out of memory during import.

  • log
  • csv
  • gis
  • ip
  • geolocation
  • maxmind
  • geodjango
  • import
Read More

3110 snippets posted so far.