Login

All snippets written in Python

Snippet List

Ensure ugettext is available absolutely everywhere

Put this into the __init.py__ file in the root of your project (the same directory level as urls.py and settings.py) and this installs _() as a global reference into the current running python VM, and now it’s as universally available as int(), map(), or str(). This is, of course, controversial. Modifying the python global namespace to add a function can be considered maintenance-hostile. But the gettext feature is so universal– at least to me– that __init__.py is where it belongs.

  • internationalization
  • gettext
Read More

RequestMiddleware

Add RequestMiddleware to your MIDDLEWARE_CLASSES settings Then, when you need request in special cases, call get_request(), which returns the request object. This has to be used in very special cases.

  • middleware
  • threading
  • request
  • local
Read More

Profanity Function (Disemvowel)

A better way of dealing w/profanity - disemvowel it! From [Wikipedia](http://en.wikipedia.org/wiki/Disemvoweling), "disemvoweling is a technique used to censor unwanted postings such as spam, internet trolling, rudeness or criticism and yet maintain some transparency, both of the act and the underlying word." Credit: Boing Boing Example: This original sentence: In the fields of Internet discussion and forum moderation, disemvoweling (also spelled disemvowelling) is the removal of vowels from text. would be disemvowelled to look like this: n th flds f ntrnt dscssn nd frm mdrtn, dsmvwlng (ls splld dsmvwllng) s th rmvl f vwls frm txt. Usage: body_input = form.cleaned_data["body"] body_input = disemvowel_profanity(body_input)

  • profanity
  • disemvowel
Read More

Ensure submitted slugs do not conflict with existing resolvable URLs

This code overrides the existing RegistrationForm in django-registration and adds a new validation step. In this step, the username (my example slug) is compared against all the existing URLs that the application currently resolves and, if it *does* successfully resolve, throws a validation exception. This indicates that the username chosen would be overriden (or, if you wrote your urls.py file badly, would override) an existing URL already recognized by your application. A much longer explanation can be found at [Dynamic names as first-level URL path objects in Django](http://www.elfsternberg.com/2009/06/26/dynamic-names-as-first-level-url-path-objects-in-django/).

  • registration
  • slug
  • reverse
  • resolve
Read More

Testing with unmanaged models

Many of my projects heavily depend on other non-django projects to create the databases. To simplify setting up a test environment, I modified the simple test runner so that it will treat all models as managed. This will also allow for easier test set up against models that point to views. You can directly populate the view with the specific data needed for the tests, instead of populating (potentially) several models.

  • model
  • test
  • managed
Read More

Template-Filter for Feedparser-Dates

A filter that changes a preparsed date from [Ultimate Feedparser](http://www.feedparser.org/) to a regular datetime instance. Now you can -for example- pass a feed parsed by feedparser to a template and do this: {% for item in feed.entries %} Title: {{ item.title }}<br /> Date: {{ item.updated_parsed|feedparsed|date:"Y-m-d" }} {% endfor %}

  • template-filter
  • datetime
  • date
  • feedparser
Read More

invalidation of cache-template-tag cache

this function invalidates a template-fragment cache bit. say you have: {% load cache %} {% cache 600 user_cache user.id %} something expensive here {% endcache %} maybe you want to force an update. With this function you can, just call: invalidate_template_cache("user_cache", user.id)

  • template
  • cache
  • invalidate
Read More

A tip for preserving GET arguments with pagination

This snippet shows a way to preserve GET arguments with pagination. Many people make mistakes to omit the query arguments besides page arguments for the pagination, and making sure correct may sphagettize your code.

  • template
  • get
  • view
  • pagination
  • arguments
Read More

Templatetag for granular permissions

If you're using [Django granular permissions](http://code.google.com/p/django-granular-permissions/), this templatetag may be useful. It enables you to check permission in templates, as mentioned in the code: {% has_row_perm user object "staff" as some_var %} {% if some_var %} ... {% endif %} To be used in `if` statements, it always saves the result to the indicated context variable. Put the snippet in row_perms.py in yourapp.templatetags package, and use `{% load row_perms %}` at your template.

  • template
  • templatetag
Read More

Email or username authentication with masquerading

This backend will allow you to have users login using either their username or the email address as it is in the User model. In addition, it will allow anyone with the staff priveleges to login as another user. The method is to user the user you wish to masquerade as (either email/username) as the username and then a string of the format *username*/*password* as the password, where *username* is the username of the staff member, and *password* is their password.

  • authentication
  • email
  • login
  • auth
  • backend
Read More

Generic AJAX app

This is based on the Admin app functionality for dispatching calls. Once you put these two files in place then add the following to urls.py: from myProject import ajax urlpatterns = patterns('', ... # Add this to the urlpatterns list (r'^ajax/(.*)', ajax.dispatcher.urls), ...) you register a function or method with a name like so: from django.contrib import ajax def myAutoCompleteCall(request): ... ajax.dispatcher.register('myAutoComplete', myAutoCompleteCall) Then you can use the url: `http://www.mysite.com/ajax/myAutoComplete` Previously I had placed this app in the django\\contrib directory because I wanted to use it in an Admin app mod. Since the release of 1.1 I was able to move it out into a standard app because of the new `formfield_overrides` property of the `ModelAdmin` class.

  • ajax
  • django
Read More

Automating URLs

This might be a bit cludgy. But the idea is to extend model definition with mixins that can help with defining standard views. So defining a new model as inheriting from Model and All, would allow automatic definition of /get /post type accessors.

  • rest
  • url
Read More

Custom CSS class in Form with template tag filter

A lot of times we need to insert a specific **CSS class** into a Form instance for it to be rendered in the template. The current method is to specify the CSS class in the Python code through the form field widget. But it would be easier for the designer to be able to specify the CSS class in the template directly. For example rather than doing this in your Python code: 'name = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))` You can do this in your template: `{{ form.name|cssclass:"special"}}` This template filter only works with Form Field instance.

  • css
  • form
  • class
Read More

2956 snippets posted so far.