Login

All snippets written in Python

Snippet List

ModelValue for djagno-livesettings

Extension for django-livesettings project - http://bitbucket.org/bkroeze/django-livesettings/ Allow to specify the model instance in settings Usage: config_register( ModelValue(BASE_GROUP, 'TestValue', queryset = Value.objects.all(), required=False)

  • livesettings
Read More

Parse custom template tag's args or kwargs

Enhanced version of snippet [1113](http://djangosnippets.org/snippets/1113/) Usage example (not self-contained): @register.tag def groupurl(parser, token): ''' Syntax:: {% groupurl view_name group [key=val, [key=val, ...]] [as varname] %} Example:: <a href="{% groupurl blog_detail group slug=blog.slug %}">{{ blog.name }}</a> ''' bits = token.contents.split() tag_name = bits[0] if len(bits) < 3: raise template.TemplateSyntaxError("'%s' takes tag at least 2 arguments (path to a view and a group)" % (tag_name,) bits_iter = iter(bits[1:]) # view_name + group and url kwargs args, kwargs = parse_args_and_kwargs(parser, bits_iter, stop_test='as', tagname=tag_name) if len(args) != 2: raise template.TemplateSyntaxError("'%s' takes exactly two non-kwargs (path to a view and a group)" % (tag_name,)) view_name, group = args # as var asvar = None for bit in bits_iter: asvar = bit return GroupURLNode(view_name, group, kwargs, asvar)

  • tag
  • templatetag
  • parse
  • args
  • kwargs
Read More

One step up from __icontains

The [REGEX and IREGEX](http://docs.djangoproject.com/en/dev/ref/models/querysets/#iregex) operators were added in Django 1.0 and I'm sure you can think of fancier ways of doing word delimiting and things like that but this was all I needed to make a user-friendly autocomplete search function.

  • ORM
  • QuerySet
Read More

Access transparently the user profile information

Splitting the information about a user across two models (User and UserProfile) is not to everyone's liking. This snippet monkeypatches the User model so that users can access transparently their profile information while still storing the data in two tables under the hood. Thus it is similar to the inheritance approach (http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/) but has the benefit of (a) not requiring a custom authentication backend or middleware and (b) loading the profile instance lazily, so there's no extra overhead if the profile infromation is not accessed. Read the docstrings for more details.

  • auth
  • profie
  • user profile
Read More

Google Account authentication

Use django_openid_auth from https://launchpad.net/django-openid-auth to authenticate your users with their Google Account. This snippet will allow your users having a Google Account address as username to log in using it.

  • authentication
  • openid
  • google-account
Read More

Silk icon tags

This simple template tag can be used to add famfamfam's silk icons easily to any element in your template.

  • templatetags
  • icons
  • silk
Read More

Management command decorator

A quick-and-dirty, and extremely simple, decorator to turn a simple function into a management command. This still requires you to have the management directory structure, but allows you to name your primary method whatever you want, and encapsulates the basic functionality of an argument-accepting management commmand. The function's docstring will be used for the command's help text if the `help` arg is not passed to the decorator. Simple usage: from myapp.utils import command @command() def my_command(): print "Hello, world" I'm not too familiar with the intricacies of decorators and management commands, so this could probably (most likely) be improved upon, but it's a start. **Update**: I've taken this a bit farther and put my work up on bitbucket: https://bitbucket.org/eternicode/django-management-decorators/src

  • decorator
  • management
  • command
Read More

Decouple 'help_text' attribute from field definition

I found model definitions with large number of fields with long help_text unreadable and feel that help_text doesn't really belong to field definition. With this snippet help_text attributes can live outside field definitions in inner HelpText class so field definitions become shorter and more readable. Usage: from django.db import models import readable_models class MyModel(models.Model): __metaclass__ = readable_models.ModelBase name = models.CharField('Name', max_length=30) address = models.CharField('Address', max_length=255) # ... long list of fields class HelpText: name = 'The name ...' address = 'Example: <very verbose example is here>'

  • models
  • help_text
Read More

Get current user without a request object

Mechanism to obtain a `request.user` object without the `request` object itself. Requires `LocalUserMiddleware` in `MIDDLEWARE_CLASSES` settings variable. **Important**: works under assumption that within a web server each request is handled by a separate thread (as for example in the Apache HTTP server). **Beware**: [security threat](http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser), although ["thread locals only appears to be a security threat if a system has already been seriously compromised, at which point there'd be easier attacks to execute"](http://groups.google.com/group/django-users/browse_thread/thread/e7af359d7d183e04). **Dev note**: works fine with one-threaded Django's development server, each request resets current user; no worries 'bout many media requests - they won't (at least shouldn't) be using Django on the production server. **Ref**: originally found in the gatekeeper app.

  • middleware
  • user
  • request
  • local thread
Read More

slug_and_slash_to_dash - modified slugify for urls

This filter converts slashes to spaces in a a sting and then slugify's the result. However, it ignores leading and trailing slashes. For example, it can take something like this: /some/url/with-an-existing-slug/ And turn it into this: some-url-with-an-existing-slug The filter was originally written to use the *curent* url as the `disqus_identifier` for Disqus comments. For example: {{ request.META.PATH_INFO|slug_and_slash_to_dash }}

  • template
  • filter
  • slugify
Read More

Amazon's CloudFront streaming signed urls

You can use this code to sign urls for streaming distributions or change it a bit and sign normal distribution's urls. Available settings: CLOUDFRONT_KEY - path to private key file CLOUDFRONT_KEY_PAIR_ID - key pair id CLOUDFRONT_EXPIRES_IN - expiration time in seconds CLOUDFRONT_DOMAIN - domain name

  • s3
  • amazon
  • aws
  • cloudfront
Read More

Overwriting file storage

The title says it all — a subclass of FileSystemStorage which will overwrite files. Note that saves which fail part way though will leave the original file intact (see `test_upload_fails`). Based roughly on http://djangosnippets.org/snippets/2044/ .

  • file
  • storage
  • filestorage
  • file-storage
Read More

2955 snippets posted so far.