Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning after overwriting get_form

In my ClassBased Update/Create Views I added some 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 the "get_form" I got the warning:

RemovedInDjango110Warning: Index.views.IndexCreateView.get_form method must define a default value for its form_class argument.

How to define a default value?

like image 274
spitzbuaamy Avatar asked Feb 16 '16 10:02

spitzbuaamy


2 Answers

The form_class argument has been optional since Django 1.8 (release notes). The warning is telling you that you must specify a default argument for form_class, e.g.

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 isn't specified. Since you already call super() in your get_form method, you should be able to use None as the default as well.

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

In your specific case, you could define a model form that changes the widget attrs in the __init__ method. Then you won't 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')
like image 186
Alasdair Avatar answered Sep 24 '22 19:09

Alasdair


Add the property form_class to your class.

class IndexCreateView(UpdateView):
    form_class = MyFormClass
like image 22
Henrik Andersson Avatar answered Sep 22 '22 19:09

Henrik Andersson