Skip to content

Instantly share code, notes, and snippets.

@elena
Created October 19, 2012 01:25
Show Gist options
  • Save elena/3915748 to your computer and use it in GitHub Desktop.
Save elena/3915748 to your computer and use it in GitHub Desktop.
Super Basic Django MultiValueField / MutliWidget example
"""
An example of minimum requirements to make MultiValueField-MultiWidget for Django forms.
"""
import pickle
from django.http import HttpResponse
from django import forms
from django.template import Context, Template
from django.views.decorators.csrf import csrf_exempt
class MultiWidgetBasic(forms.widgets.MultiWidget):
def __init__(self, attrs=None):
widgets = [forms.TextInput(),
forms.TextInput()]
super(MultiWidgetBasic, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
return pickle.loads(value)
else:
return ['', '']
class MultiExampleField(forms.fields.MultiValueField):
widget = MultiWidgetBasic
def __init__(self, *args, **kwargs):
list_fields = [forms.fields.CharField(max_length=31),
forms.fields.CharField(max_length=31)]
super(MultiExampleField, self).__init__(list_fields, *args, **kwargs)
def compress(self, values):
## compress list to single object
## eg. date() >> u'31/12/2012'
return pickle.dumps(values)
class FormForm(forms.Form):
a = forms.BooleanField()
b = forms.CharField(max_length=32)
c = forms.CharField(max_length=32, widget=forms.widgets.Textarea())
d = forms.CharField(max_length=32, widget=forms.widgets.SplitDateTimeWidget())
e = forms.CharField(max_length=32, widget=MultiWidgetBasic())
f = MultiExampleField()
@csrf_exempt
def page(request):
form = FormForm()
if request.method == 'POST':
form = FormForm(request.POST)
t = Template("""<form method="post" action=".">{{f}}<input type="submit"><form>""")
c = {'f': form.as_p()}
return HttpResponse(t.render(Context(c)))
@sibartlett
Copy link

Thank you! This was a really useful example. 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment