Login

All snippets written in Python

Snippet List

DateTimeField with microseconds

Use this in your form if you want to accept input in microseconds. In a ModelForm you can override the field like this: def __init__(self, *arg, **kwargs): super(MyForm, self).__init__(*arg, **kwargs) self.fields['date'] = DateTimeWithUsecsField() *Update* May 26 2009 - Updated to address a couple issues with this approach. See http://code.djangoproject.com/ticket/9459

  • forms
  • datetimefield
  • microseconds
Read More

Language-aware template inclusion

Looks up for a template based on the template-name plus the current users language code. Loads the template and renders it with the current context. Example:: {% langinclude "foo/some_include.html" %} Based on the users LANGUAGE_CODE, assumed we have 'de', it tries to render the template 'foo/some_include.html.de'. If that doesn't exists, it renders the template 'foo/some_include.html'. This is the default behavior of the include-Tag. Basically this is a shortcut for the following code, just with a fallback for the default template:: {% ifequal LANGUAGE_CODE "de" %} {% include "foo/some_include.html.de" %} {% else %} {% include "foo/some_include.html" %} {% endifequal %} --- Ein deutscher [Weblogeintrag mit Beschreibung](http://www.mahner.org/weblog/sprachabhangige-template-imports/)

  • templatetag
  • i18n
  • language
  • include
Read More

Readonly fields on Form/Modelform

A Form and ModelForm which provides the ability to specify certain fields as readonly, meaning that they will display their value as text wrapped with a <span> tag. The user is unable to edit them, and they are protected from POST data insertion attacks. The recommended usage is to place a NewMeta inner class on the form, with a readonly attribute which is a list or tuple of fields, similar to the fields and exclude attributes on the Meta inner class. class MyForm(ReadonlyForm): foo = forms.TextField() bar = forms.TextField() class NewMeta: readonly = ('foo',) Use these forms as you would a standard form in your templates.

  • forms
  • field
  • readonly
  • modelforms
  • span
Read More

Signal to post new saved objects to Twitter

Post new saved objects to Twitter. **Example:** from django.db import models class MyModel(models.Model): text = models.CharField(max_length=255) link = models.CharField(max_length=255) def __unicode__(self): return u'%s' % self.text def get_absolute_url(self): return self.link # the following method is optional def get_twitter_message(self): return u'my-custom-twitter-message: %s - %s' % (self.text, self.link) models.signals.post_save.connect(post_to_twitter, sender=MyModel)

  • twitter
  • signal
Read More

Load customized SQL

A management.py loading customized SQL feeding it raw to the database backend. Just put it as `management.py` in your app and put whatever SQL you want run after syncdb in `app/sql/custom.backend_driver.sql`. If the `backend_driver` is skipped the SQL will be loaded no matter database backend. Since it is run after syncdb it will also be run for test.

  • sql
  • test
  • "initial
Read More

MAC address field

Supported MAC formats: aa:bb:cc:dd:ee:ff, separator : or - aabbccddeeff both lower case and upper case

  • model
  • field
  • custom-field
  • address
  • mac
Read More

Uk postcode googlemap templetag

Entirely based on and with big thanks to: [http://www.tomanthony.co.uk/](http://www.tomanthony.co.uk/) Drops in a googlemap with a placemarker based on a uk postcode Looks like this: {% googlemap_from_ukpostcode postcode "XxY" zoom %} e.g. {% googlemap_from_ukpostcode "SP27AS" "220x290" 16 %} postcode and zoom can optionally be template variables. "XxY" is the x/y size of the map you want to drop in. zoom can be omitted and defaults to 14. requires: in settings: GOOGLE_AJAX_API_KEY, GOOGLE_MAPS_API_KEY google_map_ukpostcodes.js: is slight variation on js at http://www.tomanthony.co.uk/demo/geocode_uk_postcode/gmap.js For further and better info see: [http://www.tomanthony.co.uk/blog/geocoding-uk-postcodes-with-google-map-api/](http://www.tomanthony.co.uk/blog/geocoding-uk-postcodes-with-google-map-api/)

  • templatetag
  • googlemap
  • postcode
Read More

NonceField for disabling autocompletion

For disabling autocomplete and security purpose, this snippet defines a CharField with a randomness name for each request of the form. This is useful for turning off autocomplete for credit card input in all browsers, without breaking the xhtml validation. * [https://wiki.mozilla.org/The_autocomplete_attribute_and_web_documents_using_XHTML#Security](https://wiki.mozilla.org/The_autocomplete_attribute_and_web_documents_using_XHTML#Security) * [http://en.wikipedia.org/wiki/Cryptographic_nonce](http://en.wikipedia.org/wiki/Cryptographic_nonce)

  • fields
  • forms
  • validation
  • security
  • form
  • field
  • autocomplete
  • formfield
  • nonce
Read More

Profanity Filter Middleware

I wanted a global way to filter profanity w/out having to modify every model, view, or form. While middleware takes overhead, this technique is intended mainly for sites w/few postbacks. Hopefully this snippet will lead to more/better techniques in the comments below. Usage (settings.py): MIDDLEWARE_CLASSES = ( 'PROJECT_NAME.FILE_NAME.ProfanityFilterMiddleware', )

  • middleware
  • profanity
Read More

MarkupField

This is a field that allows multiple markup types but also stores the pre-rendered result in the database which offers an advantage over calling one of the render methods each time. Example usage looks like: class BlogPost(models.Model): ... post = MarkupField() the various extra fields can then be accessed as follows: BlogPost.objects.get(pk=1).post # raw content BlogPost.objects.get(pk=1).post_markup_type # markup type (plain text, html, markdown, rest, textile) BlogPost.objects.get(pk=1).post_rendered # content of post rendered to html BlogPost.objects.get(pk=1).post_as_html # property that access post_rendered but marked safe for easy use in templates After writing my initial version of this I was pointed at the similar http://www.djangosnippets.org/snippets/1169/ I find mine a bit more useful as it includes ReST and includes a mark_safe call to allow showing the rendered HTML directly. I have however borrowed the nice idea of dynamically building MARKUP_TYPES from #1169. Also available via http://gist.github.com/67724.

  • fields
  • rest
  • markup
  • markdown
  • textile
  • restructuredtext
Read More
Author: jpt
  • 8
  • 16

SWFUpload auth decorator

I use this snippet to simplify my auth system with flash uploader SWFUpload. flash_login_required ensures that the user is authenticated and inject the context dictionnary into the specified template. To redirect a user, just set the variable `context['redirect']` with an url. Remember to include the cookie js in your template to get the sessionid variable POSTed to your view: `<script type="text/javascript" src="/static/js/swfupload/swfupload.cookies.js"></script>`

  • authentication
  • decorator
  • auth
  • swfupload
  • login_required
Read More

Saving passwords for other services (semi-)securely in a database

I've often found myself wanting to store passwords for other web services (e.g. maillist managers, IMAP accounts, IM accounts etc) for use by a web application, but have not wanted to hard-code them in `settings.py` or store them as plaintext in the database. This uses the [pycrypto][] library to encrypt each bit of information using the concatenation of a salt value and the SECRET_KEY value from your `settings.py`, hopefully leading to a bit more security and flexibility. [pycrypto]:http://www.dlitz.net/software/pycrypto/ You'll probably want to add some views to let people edit these things as I can't find a way to make the admin interface play nicely with it. **Example usage:** In [1]: p = Password( name='IMAP account', slug='imap', username='example', password='password', host='imap.gmail.com' ) In [2]: p.host Out[2]: 'imap.gmail.com' In [3]: p.e_host Out[3]: '6wdyMDKYy8c=$YXw6t/Q9wI[...]' In [4]: p.save()

  • password
  • crypto
Read More

inclusion tag with template as variable

Sometimes you need to write a tag that renders other template, but the template name depends on template tag arguments. Usually you use simple_tag or write your own Node class. Here is a simple aproach that uses inclusion_tag. This way you can use context objects when used with takes_context=True

  • template
  • tag
Read More

Full-Text Searchable Models

A drop-in module to allow for full-text searchable models with very little effort. Tested with PostgreSQL 8.3, but should work on earlier versions with the tsearch2 module installed.

  • models
  • search
  • full-text
  • tsearch2
Read More

ifcontains tag

Django does not have ability to write {% if "item" in list %}, so I had to write this tag. It can be used just like ifequal tag

  • tag
  • if
  • ifcontains
  • block-tag
Read More

2956 snippets posted so far.