Snippet List
This is a very flexible and concise way to [Handle choices the right way](http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/) in model fields.
* Preserves order.
* Allows both a human-readable value for display in form `<select>`s as well as a code-friendly short name.
* Mimic's Django's canonical [choices format](http://docs.djangoproject.com/en/1.3/ref/models/fields/#choices).
* Doesn't restrict the value type.
* Memory efficient.
Inspired by [snippet 2373](http://djangosnippets.org/snippets/2373/) to use namedtuples as model field choices.
This allows you to access the choices (and their respective values) you create as a dictionary. It works great within django and it allows you to reference the choices as a dictionary (CHOICES[CHOICE1]) instead of CHOICES[0][0]... it is a tuple... but I mean, come on... what if you change the order? If you need the tuple just call CHOICES.choices and it will return the standard tuple.
Sometimes it is useful to have a ChoiceField which calculates its choices at runtime, when a new instance of a form containing it, is generated. And this is what `LazyChoiceField` does.
The `choices` argument must be an *iterable* as for `ChoiceField`.
**Usage example**
from django import forms
DynamicApplicationList = []
class MyForm(forms.Form):
dynamic_choice = LazyChoiceField(choices = DynamicApplicationList)
`DynamicApplicationList` can now be updated dynamically.
- fields
- choice
- forms
- form
- field
This code creates a widget that we used to generate a list of radiobuttons as follows:
* Radio button 1
--Widget__1
* Radio button 2
--Widget__2
* Radio button 3
--Widget__3
How to use it is:
`ImagenForm class (forms.ModelForm):
widget1 = forms.BooleanField ()
widget2 = forms.TextInput
widget3 = forms.ModelChoiceField (queryset = Modelo.objects.all ())
widget4 = forms.FileInput
optConListas = ChoiceWithOtherField (choices = [(2, 'widget1' widget1), (3, 'widget2' widget3.widget), (4, "widget2" widget2), (5, 'widget4' widget4)])`
- django
- choice
- choicefield
- widget
- alfonso
These three classes allows you to use enumerations (choices) in more natural model-like style. You haven't to use any magic numbers to set/get field value. And if you would like to make your enumeration a full-fledged django-model, migration should be easy.
Note, that you can subclass Item to add some context-specific attributes to it, such as `get_absolute_url()` method for instance.
Examples are provided in the form of `doctest` in the second half of the snippet.
- newforms
- choice
- model
- field
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
8 snippets posted so far.