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

后端 未结 2 1349
忘掉有多难
忘掉有多难 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,
        }
    
    0 讨论(0)
  • 2021-02-13 02:36

    Try this, with class Meta:

    from django.forms.widgets import CheckboxSelectMultiple
    from django.forms import ModelMultipleChoiceField,ModelForm
    
    from kunden.models import Kunde, Unternehmenstyp
    
    class KundeEditForm(ModelForm):
        class Meta: # model must be in the Meta class
            model = Kunde
        unternehmenstyp = ModelMultipleChoiceField(widget=CheckboxSelectMultiple,required=True, queryset=Unternehmenstyp.objects.all())
    

    REF: https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/#modelform

    You can also use modelform factories if you only need to make a simple override:

    from django.views.generic.edit import UpdateView
    from django.forms.models import modelform_factory
    
    from kunden.models import Kunde, Unternehmenstyp
    
    class KundeUpdate(UpdateView):
        model = Kunde
        form_class =  modelform_factory(Kunde,
            widgets={"unternehmenstyp": CheckboxSelectMultiple })
        template_name = 'kunden/kunde_update.html'
        success_url = '/'
    

    REF: https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/#modelform-factory-function

    0 讨论(0)
提交回复
热议问题