File: forms.py

package info (click to toggle)
python-crispy-bootstrap4 2024.10-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 660 kB
  • sloc: python: 1,994; sh: 6; makefile: 4
file content (279 lines) | stat: -rw-r--r-- 7,551 bytes parent folder | download
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
from crispy_forms.helper import FormHelper
from django import forms
from django.db import models


class SampleForm(forms.Form):
    is_company = forms.CharField(
        label="company", required=False, widget=forms.CheckboxInput()
    )
    email = forms.EmailField(
        label="email",
        max_length=30,
        required=True,
        widget=forms.TextInput(),
        help_text="Insert your email",
    )
    password1 = forms.CharField(
        label="password", max_length=30, required=True, widget=forms.PasswordInput()
    )
    password2 = forms.CharField(
        label="re-enter password",
        max_length=30,
        required=True,
        widget=forms.PasswordInput(),
    )
    first_name = forms.CharField(
        label="first name", max_length=5, required=True, widget=forms.TextInput()
    )
    last_name = forms.CharField(
        label="last name", max_length=5, required=True, widget=forms.TextInput()
    )
    datetime_field = forms.SplitDateTimeField(
        label="date time", widget=forms.SplitDateTimeWidget()
    )

    def clean(self):
        super().clean()
        password1 = self.cleaned_data.get("password1", None)
        password2 = self.cleaned_data.get("password2", None)
        if not password1 and not password2 or password1 != password2:
            raise forms.ValidationError("Passwords dont match")

        return self.cleaned_data


class SampleForm2(SampleForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper(self)


class CheckboxesSampleForm(forms.Form):
    checkboxes = forms.MultipleChoiceField(
        choices=((1, "Option one"), (2, "Option two"), (3, "Option three")),
        initial=(1,),
        widget=forms.CheckboxSelectMultiple,
    )

    alphacheckboxes = forms.MultipleChoiceField(
        choices=(
            ("option_one", "Option one"),
            ("option_two", "Option two"),
            ("option_three", "Option three"),
        ),
        initial=("option_two", "option_three"),
        widget=forms.CheckboxSelectMultiple,
    )

    numeric_multiple_checkboxes = forms.MultipleChoiceField(
        choices=((1, "Option one"), (2, "Option two"), (3, "Option three")),
        initial=(1, 2),
        widget=forms.CheckboxSelectMultiple,
    )

    inline_radios = forms.ChoiceField(
        choices=(
            ("option_one", "Option one"),
            ("option_two", "Option two"),
        ),
        widget=forms.RadioSelect,
        initial="option_two",
    )


class SelectSampleForm(forms.Form):
    select = forms.ChoiceField(
        choices=((1, "Option one"), (2, "Option two"), (3, "Option three")),
        initial=(1,),
        widget=forms.Select,
    )


class CrispyTestModel(models.Model):
    email = models.CharField(max_length=20)
    password = models.CharField(max_length=20)


class SampleForm3(forms.ModelForm):
    class Meta:
        model = CrispyTestModel
        fields = ["email", "password"]
        exclude = ["password"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper(self)


class SampleForm4(forms.ModelForm):
    class Meta:
        """
        before Django1.6, one cannot use __all__ shortcut for fields
        without getting the following error:
        django.core.exceptions.FieldError: Unknown field(s) (a, l, _) specified
        for CrispyTestModel because obviously it casts the string to a set
        """

        model = CrispyTestModel
        fields = "__all__"  # eliminate RemovedInDjango18Warning


class SampleForm5(forms.Form):
    choices = [
        (1, 1),
        (2, 2),
        (1000, 1000),
    ]
    checkbox_select_multiple = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple, choices=choices
    )
    radio_select = forms.ChoiceField(widget=forms.RadioSelect, choices=choices)
    pk = forms.IntegerField()


class SampleFormWithMedia(forms.Form):
    class Media:
        css = {"all": ("test.css",)}
        js = ("test.js",)


class SampleFormWithMultiValueField(forms.Form):
    multi = forms.SplitDateTimeField()


class CrispyEmptyChoiceTestModel(models.Model):
    fruit = models.CharField(
        choices=[("apple", "Apple"), ("pear", "Pear")],
        null=True,
        blank=True,
        max_length=20,
    )


class SampleForm6(forms.ModelForm):
    class Meta:
        """
        When allowing null=True in a model field,
        the corresponding field will have a choice
        for the empty value.

        When the form is initialized by an instance
        with initial value None, this choice should
        be selected.
        """

        model = CrispyEmptyChoiceTestModel
        fields = ["fruit"]
        widgets = {"fruit": forms.RadioSelect()}


class SampleForm7(forms.ModelForm):
    is_company = forms.CharField(
        label="company", required=False, widget=forms.CheckboxInput()
    )
    password2 = forms.CharField(
        label="re-enter password",
        max_length=30,
        required=True,
        widget=forms.PasswordInput(),
    )

    class Meta:
        model = CrispyTestModel
        fields = ("email", "password", "password2")


class SampleForm8(forms.ModelForm):
    is_company = forms.CharField(
        label="company", required=False, widget=forms.CheckboxInput()
    )
    password2 = forms.CharField(
        label="re-enter password",
        max_length=30,
        required=True,
        widget=forms.PasswordInput(),
    )

    class Meta:
        model = CrispyTestModel
        fields = ("email", "password2", "password")


class FakeFieldFile:
    """
    Quacks like a FieldFile (has a .url and string representation), but
    doesn't require us to care about storages etc.
    """

    url = "something"

    def __str__(self):
        return self.url


class FileForm(forms.Form):
    file_field = forms.FileField(widget=forms.FileInput)
    clearable_file = forms.FileField(
        widget=forms.ClearableFileInput, required=False, initial=FakeFieldFile()
    )


class AdvancedFileForm(forms.Form):
    file_field = forms.FileField(
        widget=forms.FileInput(attrs={"class": "my-custom-class"})
    )
    clearable_file = forms.FileField(
        widget=forms.ClearableFileInput(attrs={"class": "my-custom-class"}),
        required=False,
        initial=FakeFieldFile(),
    )


class GroupedChoiceForm(forms.Form):
    choices = [
        (
            "Audio",
            [
                ("vinyl", "Vinyl"),
                ("cd", "CD"),
            ],
        ),
        (
            "Video",
            [
                ("vhs", "VHS Tape"),
                ("dvd", "DVD"),
            ],
        ),
        ("unknown", "Unknown"),
    ]
    checkbox_select_multiple = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple, choices=choices
    )
    radio = forms.MultipleChoiceField(widget=forms.RadioSelect, choices=choices)


class CustomRadioSelect(forms.RadioSelect):
    pass


class CustomCheckboxSelectMultiple(forms.CheckboxSelectMultiple):
    pass


class SampleFormCustomWidgets(forms.Form):
    inline_radios = forms.ChoiceField(
        choices=(
            ("option_one", "Option one"),
            ("option_two", "Option two"),
        ),
        widget=CustomRadioSelect,
        initial="option_two",
    )

    checkboxes = forms.MultipleChoiceField(
        choices=((1, "Option one"), (2, "Option two"), (3, "Option three")),
        initial=(1,),
        widget=CustomCheckboxSelectMultiple,
    )