Login

All snippets written in Python

Snippet List

Chunks template filter

A simple filter which divides an iterable (list, tupe, string, etc) in chunks, which can then be iterated over separately. A sample of the filter usage is given: a gallery template in which I needed to display images in a table, three images per row, one row for images followed by one row for their descriptions.

  • template
  • filter
  • chunks
  • for
  • iterable
Read More

StrictAuthentication - Auto log-out inactive users

This dead-simple piece of middleware adds a terrific security feature to django authentication. Currently, users who's accounts are de-activated still may have a cookie and a login session. This middleware destroys that session on their next request. Simply add this class into a middleware.py and add it to your settings.

  • middleware
  • authentication
  • security
  • sessions
Read More

RangeField and RangeWidget

These field and widget are util for to those fields where you can put a star and end values. It supports most of field types and widgets (tested with IntegerField, CharField and DateField / TextInput and a customized DateInput). **Example of use:** class FormSearch(forms.Form): q = forms.CharField(max_length=50, label=_('Search for')) price_range = RangeField(forms.IntegerField, required=False) **Example of use (with forced widget):** class FormSearch(forms.Form): q = forms.CharField(max_length=50, label=_('Search for')) price_range = RangeField(forms.IntegerField, widget=MyWidget)

  • forms
  • field
  • widget
  • range
Read More

Chain multiple querysets into one

This class acts as a wrapper around multiple querysets. Use it if you want to chain multiple QSs together without combining them with | or &. eg., to put title matches ahead of body matches: >>> qs1 = Event.objects.filter(## title matches ##) >>> qs2 = Event.objects.filter(## matches in other fields ##) >>> qs = MultiQuerySet(qs1, qs2) >>> len(qs) >>> paginator = Paginator(qs) >>> first_ten = qs[:10] It effectively acts as an immutable, sliceable QuerySet (with only a very limited subset of the QuerySet api)

  • queryset
  • chain
  • multi
Read More

Add URL Segments to Templates

Add this code to you your context_processors.py in your project and then install it in your settings.py TEMPLATE_CONTEXT_PROCESSORS. In your template you can print out a segment of a url by using {{ segment_1 }}. For example if you're on the page "/mysite/section1/section2/" and you used {{ segment_2 }} it would print section1. This idea was taken from Expression Engines URL Segments, http://expressionengine.com/docs/templates/globals/url_segments.html. This comes in handy if you only want to do something in your template if the page your on has a particular segment. FYI, I haven't used this in a production setting yet so it could be buggy still.

  • template
  • url
  • path
  • segment
Read More

resize to thumbnail with scale-to-fill

**So you can upload rectangular pictures but still have square thumbnails.** "Scale to **fill**" instead of the out of the box "scale to **fit**" you get with `Image.thumbnail`

  • image
  • pil
  • thumbnail
  • resize
  • imagefield
Read More

change SITE_ID on fly

Django SITE_ID is a global setting, so the site framework requires you to run multiple instances of Django; at least one for each site. But i want have one instance for multiple sites. This snippet solve this task by change SITE_ID on fly. /sorry my bad english/

  • settings
  • site_id
  • site-contrib
Read More

iPhoneMiddleware

Adds an additional template dir to settings.TEMPLATE_DIRS if the request's HTTP_USER_AGENT string has the word iPhone in it. Allows you to easily create iPhone templates.

  • middleware
  • user-agent
  • iphone
Read More

Django JQuery Autocomplete for Model Selection

This is a general JQuery Autocomplete Form Field for selecting any model instance in your forms. 1 Download jquery.1.2.6 and the jquery autocomplete plugin http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/, place theme somewhere in your media directory (in this case {{ MEDIA__URL}}/js/ 2 copy fields.py to anywhere in your python-path (in this case utils.fields) 3 create a view for the ajax request that receives a query and returns a key|value list, and register it in your urls.py 4 Just Use the fields in any form like in forms.py

  • selection
  • model
  • jquery
  • autocomplete
Read More

Encryption Fields

This provides some basic cryptographic fields using pyCrypto. All encryption/decription is done transparently and defaults to use AES. Example usage: class DefferredJunk(models.Model): semi_secret = EncryptedCharField(max_length=255)

  • model
  • field
  • encryption
Read More

simple email validation function

This very basic function I was missing in this part of the Django Documentation when creating a custom MultiEmailField: http://docs.djangoproject.com/en/dev/ref/forms/validation/

  • email
  • validation
Read More

Alternative to Captchas (Without Human Interaction)

This security field is based on the perception that spambots post data to forms in very short or very long regular intervals of time, where it takes reasonable time to fill in a form and to submit it for human beings. Instead of captcha images or Ajax-based security interaction, the SecurityField checks the time of rendering the form, and the time when it was submitted. If the interval is within the specific range (for example, from 5 seconds till 1 hour), then the submitter is considered as a human being. Otherwise the form doesn't validate. Usage example: class TestForm(forms.Form): prevent_spam = SecurityField() # ... other fields ... The concept works only for unbounded forms.

  • captcha
  • security
  • form
  • field
  • antispam
  • antibot
Read More

Multi-level (tree-ish) navigation

An old snippet I made in my first django project. Nowadays I code menus in HTML and just use the perms proxy: https://docs.djangoproject.com/en/1.0/topics/auth/#id6 Credits, (awsome persons that helped me getting it to work efficiently and for free): * Yhg1s and waveform from #python@freenode * zendak from #django@freenode Thank you!

  • menu
  • navigation
  • menubar
  • navbar
Read More

2955 snippets posted so far.