Django ブログサイト forms.py フォーム

2020/07/04 (更新:2020/11/19)

フォーム定義です。

検索フォーム

検索で使用するフォームです。
widgetを指定し入力コントロールを定義します。

SearchForm

class SearchForm(forms.Form):
    keyword = forms.CharField(
        max_length=100,
        widget=forms.TextInput(attrs={
            'id':'search-keyword',
            'class':'form-control',
        })
    )

コメントフォーム

コメント登録で使用するフォームです。

CommentForm

class CommentForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)
        self.fields['status'].required = False
        self.fields['status'].choices = models.CommentStatus.get_choices()
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'

    class Meta:
        model = models.Comment
        fields = ('name_text', 'comment_text', 'status')