Udemyで公開しているDjangoコースの一つで Djangoのクラスビューにおけるクラス変数、fields と form_class について質問をいただいた内容について、ここでご紹介いたします。
質問としては
SignupViewにはfieldsがなくて、AccountUpdateViewにはfieldsがあるのはなぜでしょうか?
というような内容のものでした(言葉は一部省略しています)。
該当のコードは以下です。
# 該当箇所のみ抜粋
class SignUpView(CreateView):
form_class = UserCreationForm # この属性
success_url = '/login/'
template_name = 'pages/login_signup.html'
...
...
class AccountUpdateView(LoginRequiredMixin, UpdateView):
model = get_user_model()
template_name = 'pages/account.html'
fields = ('username', 'email',) # この属性
success_url = '/account/'
...
正直にお伝えすると、コース作成から現時点で大分日が経っていて、こちらになぜそうしたのかを覚えていませんでした。
ということで、調べ直してみると、
公式ドキュメントにもしっかり記載されていました。
The
fieldsattribute works the same way as thefieldsattribute on the innerMetaclass onModelForm. Unless you define the form class in another way, the attribute is required and the view will raise anImproperlyConfiguredexception if it’s not.
If you specify both thefieldsandform_classattributes, anImproperlyConfiguredexception will be raised.
つまり、form_class属性を記載しない場合はfileds属性は必須で、かつ両方指定はできない、ということになります。
form_classではforms.pyなどで作成したクラスを渡します。そのクラス内でもfiledsを指定するので、重複を避けるため、どちらかだけでいいということになります。