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
|
from django import forms
from django.contrib.admin.forms import AdminAuthenticationForm, AdminPasswordChangeForm
from django.contrib.admin.helpers import ActionForm
from django.core.exceptions import ValidationError
from .models import Section
class CustomAdminAuthenticationForm(AdminAuthenticationForm):
class Media:
css = {"all": ("path/to/media.css",)}
def clean_username(self):
username = self.cleaned_data.get("username")
if username == "customform":
raise ValidationError("custom form error")
return username
class CustomAdminPasswordChangeForm(AdminPasswordChangeForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["old_password"].label = "Custom old password label"
class MediaActionForm(ActionForm):
class Media:
js = ["path/to/media.js"]
class SectionFormWithOptgroups(forms.ModelForm):
articles = forms.ChoiceField(
choices=[
("Published", [("1", "Test Article")]),
("Draft", [("2", "Other Article")]),
],
required=False,
)
class Meta:
model = Section
fields = ["name", "articles"]
class SectionFormWithObjectOptgroups(forms.ModelForm):
"""Form with model instances as optgroup keys (tests str() conversion)."""
articles = forms.ChoiceField(required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Use Section instances as optgroup keys
sections = Section.objects.all()[:2]
if sections:
self.fields["articles"].choices = [
(sections[0], [("1", "Article 1")]),
(
sections[1] if len(sections) > 1 else sections[0],
[("2", "Article 2")],
),
]
class Meta:
model = Section
fields = ["name", "articles"]
class SectionFormWithDynamicOptgroups(forms.ModelForm):
"""
Form where the field with optgroups is added dynamically in __init__.
This tests that the implementation doesn't rely on accessing the
uninstantiated form class's _meta or fields, which wouldn't work here.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Dynamically add a field with optgroups after instantiation.
self.fields["articles"] = forms.ChoiceField(
choices=[
("Category A", [("1", "Item 1"), ("2", "Item 2")]),
("Category B", [("3", "Item 3"), ("4", "Item 4")]),
],
required=False,
)
class Meta:
model = Section
fields = ["name"]
|