如何将字段添加到Django模型中以动态过滤另一个字段上的下拉列表?

时间:2019-04-10 14:46:16

标签: python django django-models django-cms django-filter

我创建了一个Django-CMS插件,该插件将ManytoManyField应用于另一个模型。在前端上创建插件时,我希望用户能够过滤ManytoManyField列表(可能太长)。 顺便说一下,这个未来已经在Django admin上了:

class ModelAdmin(admin.ModelAdmin):
    list_filter = ('field_name', )
    form = PartnerLogoTableForm

是否有可能在我的身上有类似的东西 cms_plugins.py:

class PartnerLogoTablePlugin(CMSPluginBase):
  model = LogoTablePlugin
  form = LogoTablePluginForm
  name = _('LogoTable Plugin')
  render_template = False
  search_fields = ('description',)

  def render(self, context, instance, placeholder):
    self.render_template = 'aldryn_logo_tables/plugins/%s/logotable.html' % instance.style

    context.update({
        'object': instance,
        'placeholder': placeholder,
    })
    return context


plugin_pool.register_plugin(PartnerLogoTablePlugin)

models.py:

class PartnerLogoTable(models.Model):

  name = models.CharField(_('Partner name'), max_length=255)
  image = FilerImageField(verbose_name=_('Image'), null=True, blank=True, on_delete=models.SET_NULL)
  partner_url = models.TextField(_('Partner url'), null=True, blank=True, validators=[URLValidator()])

  is_active = models.BooleanField(_('Is active'), blank=True, default=True)
  created_at = models.DateTimeField(_('Created at'), auto_now_add=True)
  updated_at = models.DateTimeField(_('Updated at'), auto_now=True)
  order = models.IntegerField(_('Order'), null=True, blank=True)

  class Meta:
    verbose_name = _('Partner Logo')
    verbose_name_plural = _('Partner Logos')
    ordering = ['order']

  def __str__(self):
    return self.name


class LogoTablePlugin(CMSPlugin):
  DEFAULT = 'default'
  LOGOTABLE_CHOICES = [
    (DEFAULT, _('Default')),
  ]

  description = models.CharField(_('Description'), max_length=255, null=True, blank=True)
  partner = models.ManyToManyField(PartnerLogoTable, verbose_name=_('Partner'))
  logo_per_row = models.IntegerField(_('Logo per line'), default=1, null=True, blank=True,
                                    validators=[MaxValueValidator(4), MinValueValidator(1)],
                                    help_text=_('Number of logos to be displayed per row'))
  style = models.CharField(_('Style'), choices=LOGOTABLE_CHOICES + get_additional_styles(), default=DEFAULT,
                         max_length=50, blank=True, null=True, )

  class Meta:
    verbose_name = _('Partner Logo Plugin')
    verbose_name_plural = _('Partner Logo Plugins')

  def __unicode__(self):
    return u'%s' % self.description

forms.py

class LogoTablePluginForm(forms.ModelForm):
  model = LogoTablePlugin

  def clean_style(self):
   .....
    return style


class PartnerLogoTableForm(forms.ModelForm):
  model = PartnerLogoTable

  def clean(self):
    ....

    return self.cleaned_data

This is how the plugin looks now

1 个答案:

答案 0 :(得分:0)

来自django-autocomplete-light

ModelSelect2Multiple似乎很适合您的用例。