Login

All snippets written in Python

Snippet List

Inspect object debugging tag

Simple template tag that allows you to inspect an object in the context for debugging. It will inspect django models and forms using introspection. Dicts and lists are formatted to truncate long data. Pretty much everything else just displays the __str__ representation + class name. Example output: http://dsanity.net/introspectiontag.html Usage: put tag code as file introspection.py in your templatetags directory. Place the html template in your template path under "inspect_object.html". Then in your template: {% load introspection %} {% inspect_object obj "test object" %} The first parameter is the object to inspect, the second is the name used for display purposes.

  • tag
  • debug
  • debugging
  • introspection
Read More

Case-insensitive lookup by default

I wanted lookups on tags to be case insensitive by default, so that things like Tag.objects.get(name='Tag') would return any similar tags (ignoring case differences), i.e. `<Tag: tag>`. This snippet makes lookup on the 'name' field case-insensitive by default, although case-sensitive lookups can still be achieved with 'name__exact'. Methods like get_or_create will work as expected and be case-insensitive.

  • model
  • tags
  • tagging
  • manager
  • case-insensitive
  • iexact
  • queryset
Read More

Pull ID from arbitrary sequence

Django does not currently allow one to pull ID values from arbitrarily named sequences. For example, if you did not create your ID column using the serial data type in PostgreSQL, you likely will not be able to use your sequences. This is quite a problem for those integrating with legacy databases. While ultimately the best place to fix this is django proper, this decorator will help people get by for now. Note that in this case, all of my sequences are named "pk_TABLENAME". You'll likely have a different convention and should update the decorator appropriately. While I could have made the pattern a parameter, it didn't seem like that would gain much here.

  • database
  • sequence
  • postgresql
Read More

autocompleter with database query

This is an improvement of snippet 253 in that it supports database queries. Implementing autocompletion for foreign keys takes a few steps: 1) Put the snippet above into <app>/widgets/autocomplete.py. 2) Create a view of your foreign key model (here: Donator) in <app>/donator/views.py: from models import Donator from widgets.autocomplete import autocomplete_response def autocomplete(request): return autocomplete_response( request.REQUEST['text'], Donator, ( 'line_1', 'line_2', 'line_3', 'line_4', 'line_5', 'line_6', 'line_7', 'line_8', '^zip_code', 'location' ) ) This view returns the autocompletion result by searching the fields in the tuple. Each word from the form field must appear at least in one database field. 3) Create a URLconf that points to this new view. 4) In the form where you need the autocompletion, define the widget of the foreign key field as an instance of AutoCompleteField: from widget.autocomplete import AutoCompleteField field.widget = AutoCompleteField( url='/donator/autocomplete/'), options={'minChars': 3} ) The url parameter is the URL connected to the view in step 3), the options dict is passed on to the Ajax.Autocompleter JavaScript object. Links: * [Snippet 253](http://www.djangosnippets.org/snippets/253/) * [Django and scriptaculous integration](http://wiki.script.aculo.us/scriptaculous/show/IntegrationWithDjango) * [Ajax.Autocompleter](http://wiki.script.aculo.us/scriptaculous/show/Ajax.Autocompleter)

  • ajax
  • selection
  • database
  • autocomplete
  • query
  • foreign-key
  • prototype
  • scriptaculous
  • protoculous
Read More

If in list template tag

Given an item and a list, check if the item is in the list ----- item = 'a' list = [1, 'b', 'a', 4] ----- {% ifinlist item list %} Yup, it's in the list {% else %} Nope, it's not in the list {% endifinlist %}

  • template
  • tag
  • list
  • in
Read More

Integrating Django with ToofPy

[ToofPy](http://pyds.muensterland.org/wiki/toolserver.html) is a python server that supports WSGI so you can integrate Django with it via the WSGI handler. There is already some default Django integration in the source, but it looked really hacked up with many `if hasdjango:` lines all over the place and hardcoded URLs. A really simple solution is to create a Tool for wrapping around Django. That is what the above file does. So I removed most of the hardcoded django lines and created the tool above. ToofPy dynamically loads tools based on paths on the filesystem, so you'll need to put the file above in the WSGI folder path. Or, if you want to pre-integrate, import the file in the _initops function of WSGIMainTool just after the code to scan the directory.

  • django
  • python
  • toofpy
  • toolserver-for-python
Read More

Switch/case tags.

Meant mostly as a demo of how to do complex block tags, here's a switch/case implementation. It's deliberately simplistic: no default cases, no multiple values for the same case, etc. This is so that you can focus on the technique. Pay particular attention to how both switch and case pull out their child nodes and save them for later rendering. This is a very useful technique for these types of "structured" template tags.

  • templatetag
  • switch
  • case
  • flow
  • logic-doesnt-belong-in-templates
Read More

Flickr Sync

This code provides a Django model for photos based on Flickr, as well as a script to perform a one-way sync between Flickr and a Django installation. *Please note that the snipped contains code for two files, update.py and a Django model.* *The two chunks are separated by:* """ END OF FLICKRUPDATE """ """ START DJANGO PHOTO MODEL Requires django-tagging (http://code.google.com/p/django-tagging/) """ My model implements tagging in the form of the wonderful django-tagging app by Jonathan Buchanan, so be sure to install it before trying to use my model. The flickrupdate.py code uses a modified version of flickerlib.py (http://code.google.com/p/flickrlib/). Flickr returns invalid XML occasionally, which Python won't stand for. I got around this by wrapping the return XML in `<flickr_root>` tags. To modify flickrlib to work with my code, simply change the this line: return self.parseData(getattr(self._serverProxy, '.'.join(n))(kwargs)) to: return self.parseData('<flickr_root>' + getattr(self._serverProxy, '.'.join(n))(kwargs) + '</flickr_root>') I hate this workaround, but I can't control what Flickr returns. flickrupdate will hadle the addition and deletion of photos, sets and tags. It will also keep track of photos' pools, although, right now, it doesn't delete unused pools. This is mostly because I don't care about unused pools hanging around. It's a simple enough addition, so I'll probably add it when I have a need. Be sure to set the appropriate information on these lines: api_key = "YOUR API KEY" api_secret = "YOUR FLICKR SECRET" flickr_uid = 'YOUR FLICKR USER ID' I hadn't seen a Django model and syncing script, so I threw these together. I hope they will be useful to those wanting start syncing their photos.

  • flickr
  • photos
  • photo
  • flicker
Read More

Create PDF files using rml and django templates

It allows you to create pdf much like normal html code taking advantage of django's template engine. It requires the trml2pdf module from [OpenReport](http://sourceforge.net/projects/openreport) and can be used like `render_to_response()`. *prompt* specifies if a "save as" dialog should be shown to the user while *filename* is the name that the browser will suggest in the save dialog.

  • templates
  • pdf
  • rml
Read More

Table

This is rough code that will allow you to create a table using a sequence. It is based on the for loop tag in django template. It works basically the same except that certain variables are set based on what cell is being rendered. The tag itself does not output any html at all. This allows for simple code and very flexible creation of nice tables/grids. Enjoy

  • table
  • grid
Read More

keeptags: strip all HTML tags from output except a specified list of elements

Django has several filters designed to sanitize HTML output, but they're either too broad (striptags, escape) or too narrow (removetags) to use when you want to allow a specified set of HTML tags in your output. Thus keeptags was born. Some of the code is essentially ripped from the Django removetags function. It's not perfect--for example, it doesn't touch attributes inside elements at all--but otherwise it works well.

  • filter
  • html
  • escape
Read More

Use class name in templates

For use in templates: {% if object|classname:"entry" %} ... class="{{ object|classname }}" ... I couldn't find simpler solution for checking weather specific object belongs to specific class name, or just to output object's class name.

  • filter
  • classname
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

linebreaksli template filter

This template filter will split a string of text on newlines and return a string of <li></li>s with a newline before every line. This is handy for taking a paragraph of text and making an <ol> or <ul> from its lines. Don't forget to register your filter with the template library first or the filter won't work.

  • filter
  • linebreaks
  • li
Read More

2956 snippets posted so far.