How does one use a custom widget with a generic UpdateView without having to redefine the entire form?

后端 未结 2 1348
忘掉有多难
忘掉有多难 2021-02-13 02:11

I have a model with a ManyToMany relation that I would like to update with a CheckBoxSelectMultiple widget while everything else uses the default generic form, but when I redefi

2条回答
  •  既然无缘
    2021-02-13 02:30

    Here's a mixin that allows you to define a widgets dictionary and still respects the fields list:

    from django.forms.models import modelform_factory
    
    class ModelFormWidgetMixin(object):
        def get_form_class(self):
            return modelform_factory(self.model, fields=self.fields, widgets=self.widgets)
    

    It can be used with CreateView, UpdateView, etc. For example:

    class KundleUpdate(ModelFormWidgetMixin, UpdateView):
        model = Kunde
        widgets = {
            'unternehmenstyp': CheckboxSelectMultiple,
        }
    

提交回复
热议问题