Login

Snippets by carljm

Snippet List

BetterForm with fieldsets and row_attrs

**NOTE**: Further development of this snippet will take place in the [django-form-utils](http://launchpad.net/django-form-utils) project. This snippet provides BetterForm and BetterModelForm classes which are subclasses of django.forms.Form and django.forms.ModelForm, respectively. BetterForm and BetterModelForm allow subdivision of forms into fieldsets which are iterable from a template, and also allow definition of row_attrs which can be accessed from the template to apply attributes to the surrounding container of a specific form field. It's frequently said that a generic form layout template is a pipe dream and in "real usage" it's necessary to manually layout forms, but in my experience the addition of fieldsets and row_attrs, plus a competent CSS designer, make it possible to create a generic template that can render useful production form markup in 95+% of cases. Usage: class MyForm(BetterForm): one = forms.CharField() two = forms.CharField() three = forms.CharField() class Meta: fieldsets = (('main', {'fields': ('two',), 'legend': ''}), ('Advanced', {'fields': ('three', 'one'), 'description': 'advanced stuff'})) row_attrs = {'one': {'style': 'display: none'}} Then in the template: {% if form.non_field_errors %}{{ form.non_field_errors }}{% endif %} {% for fieldset in form.fieldsets %} <fieldset class="fieldset_{{ fieldset.name }}"> {% if fieldset.legend %} <legend>{{ fieldset.legend }}</legend> {% endif %} {% if fieldset.description %} <p class="description">{{ fieldset.description }}</p> {% endif %} <ul> {% for field in fieldset %} {% if field.is_hidden %} {{ field }} {% else %} <li{{ field.row_attrs }}> {{ field.errors }} {{ field.label_tag }} {{ field }} </li> {% endif %} {% endfor %} </ul> </fieldset> {% endfor %}

  • fieldset
  • form
  • layout
Read More

improved generic foreign key manager

This is an improvement on [snippet 984](http://www.djangosnippets.org/snippets/984/). Read it's description and [this blog post](http://zerokspot.com/weblog/2008/08/13/genericforeignkeys-with-less-queries/) for good explanations of the problem this solves. Unlike snippet 984, this version is able to handle multiple generic foreign keys, generic foreign keys with nonstandard ct_field and fk_field names, and avoids unnecessary lookups to the ContentType table. To use, just assign an instance of GFKManager as the objects attribute of a model that has generic foreign keys. Then: MyModelWithGFKs.objects.filter(...).fetch_generic_relations() The generic related items will be bulk-fetched to minimize the number of queries.

  • foreignkey
  • generic
  • manager
  • query
  • tuning
Read More

TestSettingsManager: temporarily change settings for tests

This TestSettingsManager class takes some of the pain out of making temporary changes to settings for the purposes of a unittest or doctest. It will keep track of the original settings and let you easily revert them back when you're done. It also handles re-syncing the DB if you modify INSTALLED_APPS, which is especially handy if you have some test-only models in tests/models.py. This makes it easy to dynamically get those models synced to the DB before running your tests. Sample doctest usage, for testing an app called "app_under_test," that has a tests/ sub-module containing a urls.py for testing URLs, a models.py with some testing models, and a templates/ directory with test templates: >>> from test_utils import TestManager; mgr = TestManager() >>> import os >>> mgr.set(INSTALLED_APPS=('django.contrib.contenttypes', ... 'django.contrib.sessions', ... 'django.contrib.auth', ... 'app_under_test', ... 'app_under_test.tests'), ... ROOT_URLCONF='app_under_test.tests.urls', ... TEMPLATE_DIRS=(os.path.join(os.path.dirname(__file__), ... 'templates'),)) ...do your doctests... >>> mgr.revert()

  • settings
  • test
  • syncdb
Read More

object-oriented generic views

Here's an example of writing generic views in an object-oriented style, which allows for very fine-grained customization via subclassing. The snippet includes generic create and update views which are backwards compatible with Django's versions. To use one of these generic views, it should be wrapped in a function that creates a new instance of the view object and calls it: def create_object(request, *args, **kwargs): return CreateObjectView()(request, *args, **kwargs) If an instance of one of these views is placed directly in the URLconf without such a wrapper, it will not be thread-safe.

  • views
  • generic
  • object
  • update
  • create
Read More

ModelForm-based create_update generic views

This is a ModelForms-based rewrite of the create_object and update_object generic views, with a few added features. The views now accept a "form_class" argument optionally in place of the "model" argument, so you can create and tweak your own ModelForm to pass in. They also accept a "pre_save" callback that can make any additional changes to the created or updated instance (based on request.user, for instance) before it is saved to the DB. Usage: just save the code in a file anywhere on the PythonPath and use the create_object and update_object functions as views in your urls.py.

  • newforms
  • views
  • generic
  • update
  • modelforms
  • create
Read More

MarkdownTextField

A [common pattern in Django](http://code.djangoproject.com/wiki/UsingMarkup) is to create a TextField intended for Markdown text (i.e. description) and a companion non-editable TextField for storing the HTML version (i.e. description_html), so the Markdown converter need not be run for every page view. This snippet is a custom field which encapsulates this pattern in a single field which can automatically create and update its companion HTML field. Usage: class MyModel(models.Model): description = MarkdownTextField()

  • model
  • markdown
  • field
Read More

YAAS (Yet Another Auto Slug)

This is the self-populating AutoSlugField I use. It's not the [first such snippet](http://www.djangosnippets.org/tags/slug/), but (IMO) it works a bit more cleanly. It numbers duplicate slugs (to avoid IntegrityErrors on a unique slug field) using an "ask-forgiveness-not-permission" model, which avoids extra queries at each save. And it's simply a custom field, which means adding it to a model is one line. Usage: class MyModel(models.Model): name = models.CharField(max_length=50) slug = AutoSlugField(populate_from='name')

  • slug
Read More

carljm has posted 7 snippets.