CommaSeparatedIntegerField with CheckboxSelectMultiple Widget

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from django.forms import MultipleChoiceField
from django.forms.widgets import CheckboxSelectMultiple


# Widget
class CSICheckboxSelectMultiple(CheckboxSelectMultiple):
    def value_from_datadict(self, data, files, name):
        # Return a string of comma separated integers since the database, and
        # field expect a string (not a list).
        return ','.join(data.getlist(name))

    def render(self, name, value, attrs=None, choices=()):
        # Convert comma separated integer string to a list, since the checkbox
        # rendering code expects a list (not a string)
        if value:
            value = value.split(',')
        return super(CSICheckboxSelectMultiple, self).render(
            name, value, attrs=attrs, choices=choices
        )


# Form field
class CSIMultipleChoiceField(MultipleChoiceField):
    widget = CSICheckboxSelectMultiple

    # Value is stored and retrieved as a string of comma separated
    # integers. We don't want to do processing to convert the value to
    # a list like the normal MultipleChoiceField does.
    def to_python(self, value):
        return value

    def validate(self, value):
        # If we have a value, then we know it is a string of comma separated
        # integers. To use the MultipleChoiceField validator, we first have
        # to convert the value to a list.
        if value:
            value = value.split(',')
        super(CSIMultipleChoiceField, self).validate(value)

##########
# Example
##########

# models.py
from django.db import models

CHOICE0 = 0
CHOICE1 = 1
CHOICE2 = 2
CHOICE3 = 3
MY_CHOICES = (
    (CHOICE0, 'Choice 0'),
    (CHOICE1, 'Choice 1'),
    (CHOICE2, 'Choice 2'),
    (CHOICE3, 'Choice 3'),
)


class MyModel(models.Model):
    my_csi_field = models.CommaSeparatedIntegerField(
        'comma separated ints', max_length=255, blank=True,
        default='',
        choices=MY_CHOICES
    )

# admin.py
from django.contrib import admin
from django import forms


class MyModelForm(forms.ModelForm):
    my_csi_field = CSIMultipleChoiceField(
        required=False,
    )

    class Meta:
        model = MyModel


class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm


admin.site.register(MyModel, MyModelAdmin)

More like this

  1. Allow disabling options in a checkboxselectmultiple widget by sterkh 1 year, 9 months ago
  2. Custom CheckboxSelectMultiple by martync 4 years, 6 months ago
  3. CheckboxSelectMultiple that renders in columns by rfugger 3 years, 6 months ago
  4. modular settings / site settings by mfechtner 3 years, 10 months ago
  5. MultipleChoiceCommaField by rubic 7 years, 1 month ago

Comments

(Forgotten your password?)