Login

Snippets by rubic

Snippet List

Render dynamically assigned fields in a template

**Problem:** You want to render an arbitrary number of fields assigned dynamically, as in [snippet #27](http://www.djangosnippets.org/snippets/27/), but using multiple `if` statements in a template would be tedious. **Solution:** newforms BoundField The example demonstrates a form with medication fields. We don't know in advance how many meds will be prescribed to a patient, but we want to display a minimum of 4 medication fields, each consisting of a label, name, and dosage. My code uses a cheap hack of assigning a .bf attribute to the fields during __init__, but it's easy to render in a template loop: `{% for med in form.med_list %}` *Special thanks to Honza for advice on BoundField.*

  • template
  • dynamic
  • boundfield
  • render
Read More

Using Python properties in models

After reading the comment to my [snippet #49](http://www.djangosnippets.org/snippets/49/) it occurs to me that Python properties may not be obvious to everyone, and may be underutilized in Django models. Here is a simple example demonstrating a property to format a Person's name.

  • property
  • model
Read More

ForeignKey dropdown selector

Most of the time when you want a dropdown selector based on a ForeignKey, you'll want to use [snippet #26](http://www.djangosnippets.org/snippets/26/) Here's an alternative approach, perhaps useful when you want to define choices once and reuse it in different views without overriding Form `__init__`.

  • dynamic
  • foreignkey
  • dropdown
  • choices
  • property
Read More

assign fields dynamically in newforms

DynamicFieldSnippetForm demonstrates how to dynamically assign fields in newforms. 1. weight is a required static field 2. height is an optional dynamic field This example uses `request_height` as an optional keyword argument to declare whether the `height` field should be added to the form, but it's just there for demonstration purposes. If you decide to use a keyword argument in your code, be sure to pop it off (as demonstrated in the code) or you'll get an *unexpected keyword argument* error.

  • newforms
  • dynamic
  • fields
Read More

MultipleChoiceCommaField

MultipleChoiceCommaField - CheckboxSelectMultiple value sequence as a single string, comma-separated. Since I frequently want to store multiple-selected choice items as a single field in the model, I found it convenient to write a custom field class. The code uses the comma as a separator, but it could be easily generalized to use any delimiter.

  • newforms
  • checkbox
  • multiple
  • choice
  • selection
Read More

rubic has posted 6 snippets.