SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our User Agreement and Privacy Policy.
SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our Privacy Policy and User Agreement for details.
Successfully reported this slideshow.
Activate your 14 day free trial to unlock unlimited reading.
29.
1章.Formを構成する要素:BoundFieldとField
Field
form.fields['name']
<django.forms.fields.CharField at 0x7fecdcbd7fa0>
BoundField
form['name']
<django.forms.boundfield.BoundField at 0x7fecdc936100>
29
30.
1.Formを構成する要素まとめ
Form
Field
Widget→<input>のようなHTMLをつくる
Validator→値のチェックを行う.
BoundField→各FieldのHTMLへのレンダリングとりまとめる.
30
36.
2章.フロント編:BoundField
BoundFieldはField,Formそれぞれのインスタンス化する時の引数で変更を入れられる.
class MemberForm(forms.Form):
name = forms.CharField(label='変更したラベル')
form = MemberForm(auto_id='変更したID_%s')
print(form['name'].label_tag())
<label for="変更したID_name">変更したラベル:</label>
36
39.
2章.フロント編:HTMLをレンダリング:Widget
https://docs.djangoproject.com/ja/3.2/ref/forms/widgets/
class MemberForm(forms.Form):
name = forms.CharField()
↓と同じ.
class MemberForm(forms.Form):
name = forms.CharField(
widget=forms.TextInput,
)
39
53.
3章.バリデーション編:エラーを構成するクラス
form.errors
Out[73]: {'name': ['This field is required.'], 'age': ['Enter a whole number.']}
53
54.
3章.バリデーション編:ErrorDictクラス
print(form.errors)
<ul class="errorlist">
<li>name<ul class="errorlist"><li>This field is required.</li></ul></li>
<li>age<ul class="errorlist"><li>Enter a whole number.</li></ul></li>
</ul>
__str__ メソッドでas_ul()を呼ぶようになっており,エラーメッセージのHTMLを作る
※ 一部改行とインデントを加えて表示.
54
55.
3章.バリデーション編:ErrorListクラス
再掲
form.errors
Out[73]: {'name': ['This field is required.'], 'age': ['Enter a whole number.']}
ErrorDictのvalue部分はlistに見えるが、実際はErrorListと言うクラス.
form.errors['name']
Out[74]: ['This field is required.']
print(form.errors['name'])
<ul class="errorlist"><li>This field is required.</li></ul>
__str__ メソッドでas_ul()を呼ぶようになっており,エラーメッセージのHTMLを作る
55
57.
3章.バリデーション編:ValidationErrorr例外
form.errors['name']
Out[74]: ['This field is required.']
ErrorListクラスはValidationError例外を保持している.
Validationの失敗でraiseされるのは、全てこのValidationError例外.
form.errors['name'].data
Out[84]: [ValidationError(['This field is required.'])]
57
84.
4章.FormSet
class Member(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField(null=True, blank=True)
class MemberModelForm(forms.ModelForm):
class Meta:
model = Member
fields = ('name',)
84
91.
3章.ModelFormとは
https://docs.djangoproject.com/ja/3.2/topics/forms/modelforms/
model定義
class Member(models.Model):
name = models.CharField(verbose_name='名前', max_length=100)
age = models.IntegerField(verbose_name='年齢')
Form定義
class MemberModelForm(forms.ModelForm):
class Meta:
model = Member
fields = ('name', 'age')
91