Search code examples
djangoformsdjango-viewsdjango-formsdjango-widget

How to add Widgets to UpdateView in Django


I need to add this widget to the django UpdateView,

class tlistUpdate(LoginRequiredMixin,UpdateView):
    fields = ('title', 'thumbnail', 'content', 'tags')
    model = htmlpage
    template_name = 'blog/create_form.html'

Tried adding

widgets = {
    'content': SummernoteWidget(),
}

and

content = forms.CharField(widget=SummernoteWidget())

But it did't work.


Solution

  • The UpdateView is not constructed to handle advanced form construction. The idea is that you use fields if you aim to construct a simple (standard) Form.

    You can simply construct a ModelForm and use that form in your CreateView/UpdateView:

    # app/forms.py
    
    from django import forms
    
    class HtmlPageForm(forms.ModelForm):
        class Meta:
            model = HtmlPage
            fields = ('title', 'thumbnail', 'content', 'tags')
            widgets = {
                'content': SummernoteWidget
            }

    In your views.py you can then use the form by setting the form_class attribute [Django-doc]:

    # app/views.py
    
    from app.forms import HtmlPageForm
    
    class TlistUpdate(LoginRequiredMixin,UpdateView):
        model = htmlpage
        form_class = HtmlPageForm
        template_name = 'blog/create_form.html'

    Note: normally a Django models, just like all classes in Python are given a name in PerlCase, not snake_case, so it should be: HtmlPage instead of htmlpage.