Login

All snippets written in Python

Snippet List

instant 'master' admin site

The newforms-admin branch (to be merged by 0.97, I think) is very nice to work with, separating models from the admin. It is trivial to create an admin site that includes every app that is installed. Note that you also get all your docs for things like template tags, etc.

  • admin
  • newforms-admin
Read More

BabelMiddleware

Originally posted on [skam.webfactional.com](http://skam.webfactional.com/blog/2007/07/16/babel-integration-django/) This is a very simple middleware that uses babel (http://babel.edgewall.org) for accessing locale data in request objects through request.LOCALE attribute. It also provides a function to get locale data outside views. settings.py: MIDDLEWARE_CLASSES = ( ... cut ... 'django.middleware.locale.LocaleMiddleware', 'middleware.locale.BabelMiddleware', ... cut ... )

  • middleware
  • i18n
  • l10n
  • locale
  • babel
Read More

Flash Message Template Tag

Flash message add-on for Django. Uses sessions. Behavior is such that you set a flash message in a view. That message is stored in the sesssion. Then whenever it is that the message gets displayed, it is removed from the session (never to be heard from again) **Installation:** In your settings, enable the following items. TEMPLATE_CONTEXT_PROCESSORS django.core.context_processors.request MIDDLEWARE_CLASSES django.contrib.sessions.middleware.SessionMiddleware Then put it into a file called flash.py in your templatetags directory. **Usage:** It's pretty simple. Do something like this in your view .. >>>request.session['flash_msg'] = 'Your changes have been save' >>>request.session['flash_params'] = {'type': 'success'} And maybe put something like this in your template {% load flash %} {% flash %} <h2>{{ params.type }}</h2> {{ msg }} {% endflash %} It also support a flash template, you can specify a file FLASH_TEMPLATE in your settings file and then that file will be rendered with msg and params as available variable. Usage for this would simply be `{% flash_template %}` and then you gotta make a template file that does whatever you like. Outside of that just be aware you need the Django session middleware and request context installed in your app to use this.

  • template
  • flash
  • message
Read More

Random code tag

This tag solves for me a simple need: generate random and compact codes for some of my applications. Codes are not guaranteed to be unique. **Usage** {% randomCode "num" %} **Example**: {% randomCode "8" %} generates a random 8 characters code. Create a file on your favorite template tags folder called randomcode.py and paste the code. Don't forget to include {% load randomcode %} in your templates

  • tag
Read More

DRY with common model fields

If you have many models that all share the same fields, this might be an option. Please note that order matters: Your model need to inherit from TimestampedModelBase first, and models.Model second. The fields are added directly to each model, e.g. while they will be duplicated on the database level, you only have to define them once in your python code. Not sure if there is a way to automate the call to TimestampedModelInit(). Tested with trunk rev. 5699. There is probably a slight chance that future revisions might break this.

  • models
  • model
  • inheritance
Read More

Hidden Forms

Have your forms descend from this BaseForm if you need to be able to render a valid form as hidden fields for re-submission, e.g. when showing a preview of something generated based on the form's contents. Custom form example: >>> from django import newforms as forms >>> class MyForm(HiddenBaseForm, forms.Form): ... some_field = forms.CharField() ... >>> f = MyForm({'some_field': 'test'}) >>> f.as_hidden() u'<input type="hidden" name="some_field" value="test" id="id_some_field" />' With `form_for_model`: SomeForm = forms.form_for_model(MyModel, form=HiddenBaseForm)

  • newforms
  • form
  • baseform
  • hidden
Read More

Binding pre-existing tables with dynamically created class models

This snippet proposes a solution for pre-exisiting database tables that have no counterpart in your django application models.py module. My use case was a comercial systems where pricing tables were created on-the-fly as a result of a stored procedure's execution inside the database. These pricing tables had no counterpart class model. Therefore, to access these tables from Python code you had to bypass Django's ORM and use plain-old SQL through cursos.execute(). This snippet's strategy is to create a (model) class on the fly and inject that class inside models.py namespace. After that you can use the generated class and Django's ORM machinery to access the tables, as if they were created by syncdb.

  • orm
  • dynamic-model
Read More

MetaOptions

A class called MetaOptions that enables decoration of Django models with meta classes in similar style to Admin and Meta. Included is an example usage to enable CSV export of any set of models. The package installs into django.contrib.options and is available for download at the [Python Cheeseshop](http://cheeseshop.python.org/pypi/django_options/r6)

  • csv
  • options
  • meta
Read More

nofollow filter

This filter add extra attribute **rel="nofollow"** to any "<a ..." element in the value, which does not contain it already. I use this to filter comments text in my blog.

  • filter
Read More

Feed Reader Inclusion Tag

This is an inclusion tag that can be used to pull in posts from any feed to a template. It doesn't do any caching, so it may slow down page load times. Depends on [Feedparser](http://www.feedparser.org). Template usage: {% pull_feed 'http://www.djangosnippets.org/feeds/latest/' 3 %}

  • feed
  • rss
  • inclusion-tag
Read More

Partial OpenID provider implementation from idproxy.net

Lots of people have asked me when the [django-openid](http://code.google.com/p/django-openid/) package will provide tools for running an OpenID provider (in addition to an OpenID consumer). The answer is "when it's done", but since it's such a common request I've decided to post some example code to help people who want to work it out for themselves. This is the openidserver.py file from [idproxy.net](http://idproxy.net/). It is **incomplete** - the urlconf, models, templates and some utility functions are not included. In other words, it's useless for anything other than providing a few hints as to how you can go about implementing a provider. Nonetheless, it's better than nothing. I hope this will prove a useful example for people trying to figure out how to best integrate the JanRain Python OpenID library with Django to build an OpenID provider.

  • openid
  • incomplete
  • partial
Read More

Regular Expression Dictionary

Cute little dictionary-like object that stores keys as regexs and looks up items using regex matches. It actually came in handy for a project where keys were regexes on URLs.

  • regex
  • re
  • dict
Read More

Sort Table Headers

Handles creation of `order_by` criteria based on GET parameters and provides context variables to be used when generating table header sort links which respect the current sort field and direction, reversing the direction when the same header is sorted by again. Sample view: from somewhere import SortHeaders from django.contrib.auth.models import User from django.shortcuts import render_to_response LIST_HEADERS = ( ('Username', 'username'), ('First Name', 'first_name'), ('Last Name', 'last_name'), ('Email', None), ) def user_list(request): sort_headers = SortHeaders(request, LIST_HEADERS) users = User.objects.order_by(sort_headers.get_order_by()) return render_to_response('users/user_list.html', { 'users': users, 'headers': list(sort_headers.headers()), }) Sample template: {% load my_tags %} <table cellspacing="0"> <thead> <tr> {% table_header headers %} </tr> </thead> <tbody> {% for user in users %}<tr class="{% cycle odd,even %}"> <td><a href="{{ user.get_absolute_url|escape }}">{{ user.username|escape }}</a></td> <td>{{ user.first_name|escape }}</td> <td>{{ user.last_name|escape }}</td> <td>{{ user.email|escape }}</td> </tr> {% endfor %} </tbody> </table> Sample inclusion tag: from django import template def table_header(context, headers): return { 'headers': headers, } register = template.Library() register.inclusion_tag('table_header.html', takes_context=True)(table_header) Sample inclusion tag template: {% for header in headers %}<th{{ header.class_attr }}> {% if header.sortable %}<a href="{{ header.url|escape }}">{% endif %} {{ header.text }} {% if header.sortable %}</a>{% endif %} </th>{% endfor %}

  • sort
  • table
  • headers
Read More

2956 snippets posted so far.