Login

All snippets written in Python

Snippet List

SelectDateWidget

This widget will produce a select box with the range of dates that you input. **Usage:** `widget=SelectDateWidget('2010-12-15', '2010-12-20')` **Output:** `<select> <option value="2010-12-15">Wed January 01, 2010</option> <option value="2010-12-16">Thu January 02, 2010</option> <option value="2010-12-17">Fri January 03, 2010</option> <option value="2010-12-18">Sat January 04, 2010</option> <option value="2010-12-19">Sun January 05, 2010</option> <option value="2010-12-20">Mon January 06, 2010</option> </select>`

  • datetime
  • select
  • widget
  • daterange
Read More

Semi-Portable recaptcha integration with django forms

It is not so portable and easy as I wanted it to be because of how django forms work - they don't play well with recaptcha. To get it to work: * Add two variables to your app settings, **RECAPTCHA_PUBKEY** and **RECAPTCHA_PRIVKEY** * Derive forms you want to have a captcha from the provided `ReCaptchaForm` class (how to get it working with ModelForm? any ideas?) * * If you override the form's clean method make sure you firstly call the `ReCaptchaForm`'s clean method * * In your view, upon receiving the form data initialize the objects like this `form = YouFormClassDerivedFromReCaptchaForm(remoteip=request.META['REMOTE_ADDR'], data=request.POST)` (or request.GET of course) - this is because reCaptcha needs the user's remote ip.

  • forms
  • captcha
  • recaptcha
Read More

Thumbnails in admin using django-thumbnails-works

Very straightforward way to display a thumbnail in the admin using [django-thumbnails-works](http://pypi.python.org/pypi/django-thumbnail-works) . django-thumbnails-works requires [cropresize](http://pypi.python.org/pypi/cropresize/#downloadsInstaller) (which requires and installs PIL). Add 'thumbnail_works'to INSTALLED_APPS in settings.py and here you go. Tested in django 1.3 alpha.

  • image
  • admin
  • thumbnail
Read More

Model merging function

Generic function to merge model instances. Useful when you need to merge duplicate models together, e.g. for users. Based on http://djangosnippets.org/snippets/382/, with several enhancements: * *Type checking*: only Model subclasses can be used and testing that all instances are of same model class * *Handles symmetrical many-to-may*: original snippet failed in that case * *Filling up blank attrs of original when duplicate has it filled* * *Prepared to use outside of command-line*

  • django
  • model
  • generic
  • related
  • merge
Read More

TLS(SSL) middleware, per URL pattern or whole site

Allows url patterns to include a boolean indicating whether a view requires TLS(SSL). The accompanying middleware handles the redirects needed to make sure that it upholds this requirement. **WARNING**: this monkey-patches some Django internals and is difficult to test since Django's TestClient does not support TLS. If you use this make sure you test it thouroughly. Add this to your Django settings USE_TLS = True # The default for this setting is False. URL pattern usage url(r'^login$', 'myproject.login.index', {'require_tls': True}, name='login-index'), Use `require_tls` True to force the middleware to perform redirects needed to make sure your are serving this view using https. Use `require_tls` False to force the middleware to redirect to http. Be careful with this setting, this may not behave as you expect. If you don't care if the view is served via https or http then do not include `require_tls` in the pattern. If you wish to have every view in the site served with TLS then specify the following Django setting ALWAYS_USE_TLS = True # Django setting, use TLS for every view

  • middleware
  • http
  • ssl
  • https
  • tls
Read More

Compare two instances of the same model

This compares two objects (of the same model) and returns a tuple containing dictionaries with the changed attributes. Note that ALL attributes are run through comparison, so if you are modifying non-field attributes at runtime, these will also be included. Excluded keys is a tuple containing the names if attributes you do not want to include in the comparison loop (i.e. attributes which changes are irrelevant).

  • models
  • comparison
Read More

Bit.ly url shortener

A small function to convert a url to another shortened via the bit.ly service. Requires a username and password in django settings.

  • bit.ly
  • rest-api
  • url-shortening
Read More

Prettify HTML body contents in HTTP response

This is an enhancement of snippet [#172](http://djangosnippets.org/snippets/172/). Here I use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) — far more easier to install through pip in a virtualenv, and possibly a bit more maintained — to format and properly indent the rendered HTML from templates. I also added a check to only tidy contents in a `DEBUG=True` environment, regarding high impact on performance while doing so in production. Last, it's compatible with Django 1.2.x.

  • templates
  • format
  • html
  • tidy
  • syntax
  • output
  • prettify
  • formatting
  • indentation
  • readability
Read More

Faster pagination / model object seeking (10x faster infact :o) for larger datasets (500k +)

ModelPagination Designed and Coded by Cal Leeming Many thanks to Harry Roberts for giving us a heads up on how to do this properly! ---------------------------------------------------------------------------- This is a super optimized way of paginating datasets over 1 million records. It uses MAX() rather then COUNT(), because this is super faster. EXAMPLE: >>> _t = time.time(); x = Post.objects.aggregate(Max('id')); "Took %ss"%(time.time() - _t ) 'Took 0.00103402137756s' >>> _t = time.time(); x = Post.objects.aggregate(Count('id')); "Took %ss"%(time.time() - _t ) 'Took 0.92404794693s' >>> This does mean that if you go deleting things, then the IDs won't be accurate, so if you delete 50 rows, you're exact count() isn't going to match, but this is okay for pagination, because for SEO, we want items to stay on the original page they were scanned on. If you go deleting items, then the items shift backwards through the pages, so you end up with inconsistent SEO on archive pages. If this doesn't make sense, go figure it out for yourself, its 2am in the morning ffs ;p Now, the next thing we do, is use id seeking, rather then OFFSET, because again, this is a shitton faster: EXAMPLE: >>> _t = time.time(); x = map(lambda x: x, Post.objects.filter(id__gte=400000, id__lt=400500).all()); print "Took %ss"%(time.time() - _t) Took 0.0467309951782s >>> _t = time.time(); _res = map(lambda x: x, Post.objects.all()[400000:400500]); print "Took %ss"%(time.time() - _t) Took 1.05785298347s >>> By using this seeking method (which btw, can be implemented on anything, not just pagination) on a table with 5 million rows, we are saving 0.92s on row count, and 1.01s on item grabbing. This may not seem like much, but if you have 1024 concurrent users, this will make a huge difference. If you have any questions or problems, feel free to contact me on cal.leeming [at] simplicitymedialtd.co.uk

  • model
  • pagination
  • object
  • large
  • big
  • dataset
  • faster
  • optimized
  • quicker
  • seeking
Read More

Rate Limiting Decorator

This is a small and useful decorator that you can use to protect yourself from bad users or bots hitting your site.

  • security
  • cache-based-rate-limiting
  • protection
  • rate limiting
Read More

slugify with transliteration

This slugify correctly transliterates special characters using the translitcodec package from PyPI. Make sure you've installed http://pypi.python.org/pypi/translitcodec/ before using this.

  • slug
  • slugify
  • special chars
  • trans
  • transliteration
  • umlauts
Read More

send a simple Campfire chat message from fabric script

look ma, no api! a python method for [fabric](fabfile.org) script to send a message to your [campfire](campfirenow.com) chat room. not really a django script but I didn't know where else to put it. I use it to send a deployment messages to campfire when we deploy new revisions. like the comment mentions, put your api key in ~/.fabricrc. the example api key is garbage so don't waste your time.

  • basecamp
  • campfire
  • chat
  • fabric
Read More

2955 snippets posted so far.