简体   繁体   中英

Django default queryset and widget for ModelForm custom field

I have a Site model, and I am trying to create a SiteSelectorField that extends django.forms.ModelMultipleChoiceField , that uses my custom SiteSelectorWidget and Site.objects.all() as the queryset

Without the custom form field, my forms.py code looks like this (and works):

sites = forms.ModelMultipleChoiceField(queryset=Site.objects.all(), widget=SiteSelectorWidget())

I would like to limit the arguments passed, so I can do this

sites = SiteSelectorField()

But when I create the SiteSelectorField class, as below, Django tells me "SiteSelectorField' object has no attribute 'validators"

class SiteSelectorField(forms.ModelMultipleChoiceField):

  queryset = Site.objects.all()
  widget = SiteSelectorWidget()

  def __init__(self, *args, **kwargs):
    pass

How can I specify a default queryset and widget for this field so they don't need to be passed?

Delete the def __init__ method and code. By putting "pass" inside there, you're overriding the default functionality of ModelMultipleChoiceField , which your class inherits from, that would utilize the queryset.

Edit:

Re-structure your __init__ method like so:

  def __init__(self, *args, **kwargs):
      if not 'queryset' in kwargs:
          kwargs['queryset'] = Site.objects.all()
      return super(SiteSelectorField, self).__init__(*args, **kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM