Warning after rewriting get_form

In my update / creation of ClassBased views, I added several classes:

class IndexUpdateView(UpdateView): fields = '__all__' model = Index template_name = 'index_form.html' def get_success_url(self): return reverse('IndexList') def get_form(self, form_class): form = super(IndexUpdateView, self).get_form(form_class) form.fields['year'].widget.attrs.update({"class": "form-control tosp"}) form.fields['index'].widget.attrs.update({"class": "form-control tosp"}) return form 

After adding "get_form" I got a warning:

The RemovedInDjango110Warning: Index.views.IndexCreateView.get_form method should determine the default value for its form_class argument.

How to determine the default value?

+5
source share
2 answers

The form_class argument is optional since Django 1.8 ( release notes ). A warning tells you that you must specify a default argument for form_class, for example.

 def get_form(self, form_class=MyFormClass): ... 

If you look at the default implementation , it uses None as the default and calls self.get_form_class() when it is not specified. Since you are already calling super () on your get_form method, you can also use None as the default.

 def get_form(self, form_class=None): form = super(IndexUpdateView, self).get_form(form_class) ... 

In your specific case, you can define a model form that changes the attributes of the widget in the __init__ method. Then you do not have to override get_form at all.

 class IndexForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(IndexForm, self).__init__(*args, **kwargs) self.fields['year'].widget.attrs.update({"class": "form-control tosp"}) self.fields['index'].widget.attrs.update({"class": "form-control tosp"}) class IndexUpdateView(UpdateView): fields = '__all__' model = Index form_class = IndexForm template_name = 'index_form.html' def get_success_url(self): return reverse('IndexList') 
+10
source

Add the form_class property to your class.

 class IndexCreateView(UpdateView): form_class = MyFormClass 
+1
source

Source: https://habr.com/ru/post/1243120/


All Articles