Exemple #1
0
class AuditorAdminPermissionForm(forms.ModelForm):
    name = forms.CharField(disabled=True)
    content_type = forms.ModelChoiceField(ContentType.objects.all(),
                                          disabled=True)
    codename = forms.CharField(disabled=True)
    users = forms.ModelMultipleChoiceField(
        widget=widgets.FilteredSelectMultiple("User", is_stacked=False),
        queryset=User.objects.filter(is_active=True),
        required=False,
    )
    groups = forms.ModelMultipleChoiceField(
        widget=widgets.FilteredSelectMultiple("Group", is_stacked=False),
        queryset=Group.objects.all(),
        required=False,
    )

    class Meta:
        model = Permission
        fields = (
            'name',
            'content_type',
            'codename',
            'users',
            'groups',
        )
Exemple #2
0
 def formfield_for_manytomany(self, db_field, request, **kwargs):
     print(
         "TalkAdmin.formfield_for_manytomany: db_field: {} db_field.name {} request: {}"
         .format(db_field, db_field.name, request))
     if db_field.name == "projects":
         kwargs["widget"] = widgets.FilteredSelectMultiple("projects",
                                                           is_stacked=False)
     if db_field.name == "project_umbrellas":
         kwargs["widget"] = widgets.FilteredSelectMultiple(
             "project umbrellas",
             is_stacked=False,
         )
     if db_field.name == "speakers":
         # Uncomment the following block of code to limit the speakers field in the admin UI only to current lab members
         # Note: we don't actually want to do this (see https://github.com/jonfroehlich/makeabilitylabwebsite/issues/534)
         # but keeping it here because code may be useful in the future for other areas of admin interface
         # current_member_and_collab_ids = [person.id for person in Person.objects.all() if person.is_current_member()]
         # filtered_speakers = Person.objects.filter(id__in=current_member_and_collab_ids).order_by('first_name')
         # kwargs["queryset"] = filtered_speakers
         kwargs["widget"] = widgets.FilteredSelectMultiple("speakers",
                                                           is_stacked=False)
     if db_field.name == "keywords":
         kwargs["widget"] = widgets.FilteredSelectMultiple("keywords",
                                                           is_stacked=False)
     return super(TalkAdmin,
                  self).formfield_for_manytomany(db_field, request,
                                                 **kwargs)
Exemple #3
0
class ResourceAdminForm(forms.ModelForm):
    division = forms.ModelChoiceField(
        label=FIELDS['agency_division'],
        widget=widgets.ForeignKeyRawIdWidget(
            Resource._meta.get_field('division').rel, site),
        queryset=Division.objects,
        required=False)
    categories = forms.ModelMultipleChoiceField(
        queryset=Category.objects,
        widget=widgets.FilteredSelectMultiple("categories", False))
    data_types = forms.ModelMultipleChoiceField(
        queryset=DataType.objects,
        widget=widgets.FilteredSelectMultiple("Data types", False))
    department = forms.ModelChoiceField(
        label=FIELDS['agency_name'],
        widget=widgets.ForeignKeyRawIdWidget(
            Resource._meta.get_field('department').rel, site),
        queryset=Department.objects)
    agency_type = forms.ChoiceField(choices=Resource.AGENCY_TYPES,
                                    label=FIELDS['agency_type'])
    newest_record = forms.DateField(label=FIELDS['newest_updated'],
                                    required=False,
                                    widget=widgets.AdminDateWidget)
    oldest_record = forms.DateField(label=FIELDS['oldest_record'],
                                    required=False,
                                    widget=widgets.AdminDateWidget)
    updates = forms.ModelChoiceField(label=FIELDS['update_frequency'],
                                     queryset=UpdateFrequency.objects,
                                     required=False)

    class Meta:
        model = Resource
Exemple #4
0
 def formfield_for_manytomany(self, db_field, request=None, **kwargs):
     if db_field.name == "sponsors":
         kwargs["widget"] = widgets.FilteredSelectMultiple("sponsors", is_stacked=False)
     if db_field.name == "keywords":
         kwargs["widget"] = widgets.FilteredSelectMultiple("keywords", is_stacked=False)
     if db_field.name == "project_umbrellas":
         kwargs["widget"] = widgets.FilteredSelectMultiple("project umbrellas", is_stacked=False)
     return super(ProjectAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
Exemple #5
0
class ChannelForm(forms.ModelForm):
    users = forms.ModelMultipleChoiceField(
        User.objects.all(),
        widget=widgets.FilteredSelectMultiple(_("Users"), False, attrs={}),
        required=False,
        label=_('Users'))
    owners = forms.ModelMultipleChoiceField(
        User.objects.all(),
        widget=widgets.FilteredSelectMultiple(_("Owners"), False, attrs={}),
        required=False,
        label=_('Owners'))

    def clean(self):
        cleaned_data = super(ChannelForm, self).clean()
        if 'description' in cleaned_data.keys():
            cleaned_data['description_%s' %
                         settings.LANGUAGE_CODE] = cleaned_data['description']
        if 'title' in cleaned_data.keys():
            cleaned_data['title_%s' %
                         settings.LANGUAGE_CODE] = cleaned_data['title']

    def __init__(self, *args, **kwargs):
        self.is_staff = kwargs.pop(
            'is_staff') if 'is_staff' in kwargs.keys() else self.is_staff
        self.is_superuser = kwargs.pop('is_superuser') if (
            'is_superuser' in kwargs.keys()) else self.is_superuser

        self.CHANNEL_FORM_FIELDS_HELP_TEXT = CHANNEL_FORM_FIELDS_HELP_TEXT

        super(ChannelForm, self).__init__(*args, **kwargs)
        if FILEPICKER:
            self.fields['headband'].widget = CustomFileWidget(type="image")

        if not hasattr(self, 'admin_form'):
            del self.fields['visible']

        # change ckeditor config for no staff user
        if not hasattr(self, 'admin_form') and (self.is_staff is False
                                                or self.is_superuser is False):
            del self.fields['headband']
            self.fields['description'].widget = CKEditorWidget(
                config_name='default')
            for key, value in settings.LANGUAGES:
                self.fields['description_%s' %
                            key.replace('-', '_')].widget = CKEditorWidget(
                                config_name='default')
        # hide default langage
        self.fields['description_%s' %
                    settings.LANGUAGE_CODE].widget = forms.HiddenInput()
        self.fields['title_%s' %
                    settings.LANGUAGE_CODE].widget = forms.HiddenInput()

        self.fields = add_placeholder_and_asterisk(self.fields)

    class Meta(object):
        model = Channel
        fields = '__all__'
Exemple #6
0
 def formfield_for_manytomany(self, db_field, request, **kwargs):
     print("PosterAdmin.formfield_for_manytomany: db_field: {} db_field.name {} request: {}".format(db_field, db_field.name, request))
     if db_field.name == "projects":
         kwargs["widget"] = widgets.FilteredSelectMultiple("projects", is_stacked=False)
     if db_field.name == "authors":
         kwargs["widget"] = widgets.FilteredSelectMultiple("authors", is_stacked=False)
     if db_field.name == "keywords":
         kwargs["widget"] = widgets.FilteredSelectMultiple("keywords", is_stacked=False)
     return super(PosterAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
Exemple #7
0
 class Meta:
     model = models.Group
     fields = '__all__'
     widgets = {
         'people':
         widgets.FilteredSelectMultiple(_("People"), is_stacked=False),
         'companies':
         widgets.FilteredSelectMultiple(_("Companies"), is_stacked=False),
     }
Exemple #8
0
 def formfield_for_manytomany(self, db_field, request=None, **kwargs):
     if db_field.name == "authors":
         kwargs['widget'] = SortedFilteredSelectMultiple()
     elif db_field.name == "projects":
         kwargs["widget"] = widgets.FilteredSelectMultiple("projects", is_stacked=False)
     elif db_field.name == "project_umbrellas":
         kwargs["widget"] = widgets.FilteredSelectMultiple("project umbrellas", is_stacked=False)
     elif db_field.name == "keywords":
         kwargs["widget"] = widgets.FilteredSelectMultiple("keywords", is_stacked=False)
     return super(PublicationAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
Exemple #9
0
class FilteredSelectMultipleForm(forms.Form):
    description = "FilteredSelectMultiple"
    CHOICES = ((1, 'Apple'), (2, 'Orange'), (3, 'Watermeloun'))

    field1 = forms.ChoiceField(help_text='stacked',
                               choices=CHOICES,
                               widget=widgets.FilteredSelectMultiple(
                                   verbose_name='Field One', is_stacked=True))
    field2 = forms.ChoiceField(help_text='not stacked',
                               choices=CHOICES,
                               widget=widgets.FilteredSelectMultiple(
                                   verbose_name='Field One', is_stacked=False))
Exemple #10
0
 def __init__(self, *args, **kwargs):
     super(FormAdminGaleria, self).__init__(*args, **kwargs)
     self.fields['fotos'] = forms.ModelMultipleChoiceField(
         Foto.objects.all(),
         widget=widgets.FilteredSelectMultiple(verbose_name="Fotos",
                                               is_stacked=False),
         required=False)
     self.fields['arquivo'] = forms.ModelMultipleChoiceField(
         UploadArquivo.objects.all(),
         widget=widgets.FilteredSelectMultiple(verbose_name="Arquivos",
                                               is_stacked=False),
         required=False,
         label="Arquivos")
Exemple #11
0
 def __init__(self, *args, **kwargs):
     super(DetectCyclicForm, self).__init__(*args, **kwargs)
     if 'south' in settings.INSTALLED_APPS:
         self.fields['exclude_packages'].initial = 'migrations'
     dot = pydot.Dot()
     formats = [(format, format) for format in dot.formats]
     formats.append((FORMAT_SPECIAL, FORMAT_SPECIAL))
     formats.sort()
     self.fields['format'].choices = formats
     applications_label = self.fields['applications'].label
     applications_choices = []
     for app in settings.INSTALLED_APPS:
         if not (app, app) in applications_choices:
             applications_choices.append((app, app))
     self.fields['applications'].choices = applications_choices
     applications_initial = [
         app_value for app_label, app_value in applications_choices
         if not app_value.startswith('django.')
         and app_value != 'django_detect_cyclic'
     ]
     self.fields['applications'].initial = applications_initial
     self.fields[
         'applications'].widget = widgets_admin.FilteredSelectMultiple(
             applications_label,
             is_stacked=False,
             choices=applications_choices)
Exemple #12
0
 def formfield_for_manytomany(self, db_field, request, **kwargs):
     vertical = False
     kwargs['widget'] = widgets.FilteredSelectMultiple(
         db_field.verbose_name,
         vertical,
     )
     return super(BeverageAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
Exemple #13
0
    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        """
        Get a form Field for a ManyToManyField.
        """
        # If it uses an intermediary model that isn't auto created, don't show
        # a field in admin.
        if hasattr(db_field, 'through'
                   ) and not db_field.remote_field.through._meta.auto_created:
            return None
        db = kwargs.get('using')

        if db_field.name in self.raw_id_fields:
            kwargs['widget'] = widgets.ManyToManyRawIdWidget(
                db_field.remote_field, self.admin_site, using=db)
            kwargs['help_text'] = ''
        elif db_field.name in (list(self.filter_vertical) +
                               list(self.filter_horizontal)):
            kwargs['widget'] = widgets.FilteredSelectMultiple(
                db_field.verbose_name, db_field.name in self.filter_vertical)

        if 'queryset' not in kwargs:
            queryset = self.get_field_queryset(db, db_field, request)
            if queryset is not None:
                kwargs['queryset'] = queryset

        form_field = db_field.formfield(**kwargs)
        if isinstance(form_field.widget, SelectMultiple) and not isinstance(
                form_field.widget, CheckboxSelectMultiple):
            msg = _(
                'Hold down "Control", or "Command" on a Mac, to select more than one.'
            )
            help_text = form_field.help_text
            form_field.help_text = string_concat(help_text, ' ',
                                                 msg) if help_text else msg
        return form_field
Exemple #14
0
class ShiftAdminForm(forms.ModelForm):
    """Admin form to edit shifts."""
    class Meta:
        """Meta class for ShiftAdminForm."""

        model = Shift
        exclude = []

    def __init__(self, *args, **kwargs):
        """Initialize the form."""
        super().__init__(*args, **kwargs)

        self.fields["venue"].queryset = OrderVenue.objects.filter(
            venue__active=True)
        self.fields["assignees"].queryset = User.objects.all()

        if self.instance.pk:
            self.fields["venue"].queryset = OrderVenue.objects.filter(
                Q(venue__active=True) | Q(shift=self.instance)).distinct()
            self.fields["venue"].initial = OrderVenue.objects.filter(
                shift=self.instance)
            self.fields["assignees"].initial = User.objects.filter(
                shift=self.instance)

    assignees = forms.ModelMultipleChoiceField(
        queryset=None,
        required=False,
        widget=widgets.FilteredSelectMultiple("Assignees", False),
    )
Exemple #15
0
class RoleForm(forms.Form):
    # overwrite_existing = forms.BooleanField(help_text="Overwrite existing entries", required=False)
    business_areas = forms.ModelMultipleChoiceField(queryset=BusinessArea.objects.all(),
                                                    widget=widgets.FilteredSelectMultiple('Services', False)
                                                    )
    user = forms.ModelChoiceField(queryset=User.objects.all())
    group = forms.ModelChoiceField(queryset=Group.objects.all())
Exemple #16
0
class WorkflowNodeForm(forms.ModelForm):
    outcomings = forms.MultipleChoiceField(
        choices=tuple(),
        required=False,
        widget=admin_widgets.FilteredSelectMultiple('Outcomings', False))

    class Meta:                 # pylint: disable=W0232
        model = WorkflowNode
        fields = [
            'name',
            'label',
        ]

    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=None,
                 empty_permitted=False, instance=None):
        if initial is None:
            initial = {}
        if instance is not None:
            initial.update({
                'outcomings': instance.outcomings,
            })
        super(WorkflowNodeForm, self).__init__(
            data=data, files=files, auto_id=auto_id, prefix=prefix,
            initial=initial, error_class=error_class, label_suffix=label_suffix,
            empty_permitted=empty_permitted, instance=instance)
        if instance is not None:
            self.fields['outcomings'].choices = instance.workflow.nodes.values_list('name', 'label')

    def save(self, commit=True):
        if not self.cleaned_data.get('outcomings', []):
            self.instance.outcomings = []
        return super(WorkflowNodeForm, self).save(commit=commit)
Exemple #17
0
 class Meta:
     model = OrganizationManagers
     exclude = ()
     widgets = {
         'permissions': widgets.FilteredSelectMultiple(OrganizationManagers \
                                                       ._meta.get_field('permissions').verbose_name, False)
     }
Exemple #18
0
 def formfield_for_manytomany(self, db_field, request, **kwargs):
     if (db_field.name) == "groups":
         kwargs["queryset"] = Group.objects.filter(
             groupsite__sites=Site.objects.get_current())
     kwargs['widget'] = widgets.FilteredSelectMultiple(
         db_field.verbose_name, False)
     return super().formfield_for_foreignkey(db_field, request, **kwargs)
Exemple #19
0
 def formfield_for_manytomany(self, db_field, request=None, **kwargs):
     if db_field.name == "project":
         kwargs["widget"] = widgets.FilteredSelectMultiple("project",
                                                           is_stacked=False)
     return super(NewsAdmin,
                  self).formfield_for_manytomany(db_field, request,
                                                 **kwargs)
Exemple #20
0
    def formfield(self, form_class=forms.MultipleChoiceField, **kwargs):
        """
        Returns a django.forms.Field instance for this database Field.
        
        Using super() won't work because this would replace the form_class!
        
        """
        defaults = {
          'choices': sorted(self.get_choices(include_blank=False),
                            key=lambda choice: choice[1].lower()),
          'help_text': self.help_text,
          'label': capfirst(self.verbose_name),
          'required': not self.blank,
        }

        if self.has_default():
            if callable(self.default):
                defaults['initial'] = self.default
                defaults['show_hidden_initial'] = True

            else:
                defaults['initial'] = self.get_default()
        # replace default widget
        kwargs['widget'] = widgets.FilteredSelectMultiple(self.verbose_name, False)
        defaults.update(kwargs)
        return form_class(**defaults)
Exemple #21
0
class UpdateDefaultEditorGroupForm(ModelForm):
    """
    Form used to update default editor groups.
    """
    default_editor_groups = forms.ModelMultipleChoiceField([],
                                                           widget=widgets.FilteredSelectMultiple(
                                                               _("default editor groups"),
                                                               is_stacked=False),
                                                           required=False)

    class Media:
        css = {
            # required by the FilteredSelectMultiple widget
            'all': ['{}admin/css/widgets.css'.format(settings.STATIC_URL)],
        }
        # required by the FilteredSelectMultiple widget
        js = ['/{}admin/jsi18n/'.format(settings.DJANGO_BASE)]

    class Meta:
        """
        Meta class connecting to UserProfile object model.
        """
        model = UserProfile
        exclude = ('user', 'modified', 'uuid', 'birthdate', 'affiliation', \
                   'position', 'homepage')

    def __init__(self, available_editor_group, chosen_editor_group, *args, **kwargs):
        """
        Initializes the `UpdateDefaultEditorGroupForm` with the editor groups
        of the given query set.
        """
        super(UpdateDefaultEditorGroupForm, self).__init__(*args, **kwargs)
        # If there is a list of editor groups, then modify the ModelChoiceField
        self.fields['default_editor_groups'].queryset = available_editor_group
        self.fields['default_editor_groups'].initial = chosen_editor_group
Exemple #22
0
class TraitForm(GHForm):
    charactertypes = forms.ModelMultipleChoiceField(
        queryset=CharacterType.objects.activeonly(),
        widget=forms.CheckboxSelectMultiple(),
        required=False)
    chaptertypes = forms.ModelMultipleChoiceField(
        queryset=ChapterType.objects.activeonly(),
        widget=forms.CheckboxSelectMultiple(),
        required=False)
    cotraits = forms.ModelMultipleChoiceField(
        queryset=Trait.objects.cotraits(),
        widget=widgets.FilteredSelectMultiple(verbose_name='Required Traits',
                                              is_stacked=False),
        required=False)
    bantraits = forms.ModelMultipleChoiceField(
        queryset=Trait.objects.cotraits(),
        widget=widgets.FilteredSelectMultiple(verbose_name='Banned Traits',
                                              is_stacked=False),
        required=False)
    addtraits = forms.ModelMultipleChoiceField(
        queryset=Trait.objects.cotraits(),
        widget=widgets.FilteredSelectMultiple(verbose_name='Add Traits',
                                              is_stacked=False),
        required=False)

    class Meta:
        model = Trait
        fields = [
            'name', 'type', 'level', 'isadmin', 'renamable', 'description',
            'charactertypes', 'chaptertypes', 'cotraits', 'bantraits',
            'addtraits', 'dateactive', 'dateexpiry'
        ]

    adminonlyfields = ['isadmin', 'dateactive', 'dateexpiry']
    ifields = ['type', 'name']
    fieldlist = ['id', 'name', 'level', 'xpcost', 'bpcost', 'description']
    sname = Vocabulary.objects.get(name='Trait').displayname
    surl = '/traits/'
    sheading = ''.join(['Add New ', sname])
    isadmin = True
    isprivate = False
    mname = 'Trait'

    def __init__(self, *args, **kwargs):
        super(TraitForm, self).__init__(*args, **kwargs)
        self.fields['renamable'].label = 'Can be Ranamed'
        Trait.__unicode__ = Trait.cotrait_label
Exemple #23
0
    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        kwargs['widget'] = widgets.FilteredSelectMultiple(
            db_field.verbose_name, db_field.name in self.filter_vertical)

        return super(admin.ModelAdmin,
                     self).formfield_for_manytomany(db_field,
                                                    request=request,
                                                    **kwargs)
Exemple #24
0
	class Meta:
		model = Post
		fields = ('title','description','text', 'posttags')
		widgets = {
				'text':TinyMCEWidget(),
				'description':forms.Textarea(attrs={'cols':'80','rows':'5'}),
				'posttags':admin_widgets.FilteredSelectMultiple(u'метки', 0)
			}
Exemple #25
0
	class Meta:
		model = Photo
		fields = ('title','description','image', 'tags')
		widgets = {
				'description':forms.Textarea(attrs={'cols':'80','rows':'5'}),
				'tags':admin_widgets.FilteredSelectMultiple(u'метки', 0),
				'image':admin_widgets.AdminFileWidget(attrs={})
			}
Exemple #26
0
class ResourceAdminForm(forms.ModelForm):
    description = MiniWYSIWYGField()
    division = forms.ModelChoiceField(
        label=FIELDS['agency_division'],
        widget=widgets.ForeignKeyRawIdWidget(
            Resource._meta.get_field('division').rel, site),
        queryset=Division.objects,
        required=False)
    categories = forms.ModelMultipleChoiceField(
        queryset=Category.objects,
        widget=widgets.FilteredSelectMultiple("categories", False))
    data_types = forms.ModelMultipleChoiceField(
        queryset=DataType.objects,
        widget=widgets.FilteredSelectMultiple("Data types", False))
    department = forms.ModelChoiceField(
        label=FIELDS['agency_name'],
        widget=widgets.ForeignKeyRawIdWidget(
            Resource._meta.get_field('department').rel, site),
        queryset=Department.objects)
    agency_type = forms.ChoiceField(choices=Resource.AGENCY_TYPES,
                                    label=FIELDS['agency_type'])
    newest_record = forms.DateField(label=FIELDS['newest_updated'],
                                    required=False,
                                    widget=widgets.AdminDateWidget)
    oldest_record = forms.DateField(label=FIELDS['oldest_record'],
                                    required=False,
                                    widget=widgets.AdminDateWidget)
    updates = forms.ModelChoiceField(label=FIELDS['update_frequency'],
                                     queryset=UpdateFrequency.objects,
                                     required=False)

    def clean_name(self):
        name = self.cleaned_data['name']
        if not self.instance.pk:
            slug = slugify(name)
            resources = Resource.objects.filter(slug=slug)
            if resources:
                raise forms.ValidationError(
                    "Resource with this name already exists.")
        return name

    class Meta:
        model = Resource

    class Media:
        js = ("js/wysiwyg.js", )
Exemple #27
0
	class Meta:
		model = VideoFile
		fields = ('title','description','path', 'preview', 'tags')
		widgets = {
				'preview':admin_widgets.AdminFileWidget(attrs={}),
				'path':admin_widgets.AdminFileWidget(attrs={}),
				'description':forms.Textarea(attrs={'cols':'80','rows':'5'}),
				'tags':admin_widgets.FilteredSelectMultiple(u'метки', 0)
			}
Exemple #28
0
class AdminUserChangeForm(forms.ModelForm):
    password = django.contrib.auth.forms.ReadOnlyPasswordHashField(
        help_text="Raw passwords are not stored, so there is no way to see "
        "this user's password, but you can change the password "
        'using <a href="../password/">this form</a>.')

    groups = forms.ModelMultipleChoiceField(
        queryset=models.Group.objects.all(),
        required=False,
        widget=widgets.FilteredSelectMultiple("groups", False))

    def __init__(self, *args, **kwargs):
        super(AdminUserChangeForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields["groups"].initial = self.instance.groups.all()

    def _get_validation_exclusions(self):
        exclude = super()._get_validation_exclusions()
        if self.instance:
            # Don't validate the username if it isn't changing.
            # We have some legacy usernames that now fail validation.
            exclude_if_same = ("username", )
            for field in exclude_if_same:
                new_value = self.cleaned_data.get(field)
                old_value = getattr(self.instance, field)
                if new_value == old_value:
                    exclude += [field]
        return exclude

    def save_m2m(self):
        self.instance.groups.set(self.cleaned_data["groups"])

    def save(self, *args, **kwargs):
        instance = super().save()
        self.save_m2m()
        return instance

    def clean_password(self):
        return self.initial["password"]

    class Meta:
        model = models.User
        fields = (
            "username",
            "password",
            "email",
            "email_verified",
            "is_active",
            "current_avatar",
            "twofa_enabled",
            "is_admin",
            "is_staff",
            "groups",
            "mc_username",
            "irc_nick",
            "gh_username",
        )
Exemple #29
0
 def formfield_for_manytomany(self, db_field, request=None, **kwargs):
     vertical = False  # change to True if you prefer boxes to be stacked vertically
     kwargs['widget'] = widgets.FilteredSelectMultiple(
         db_field.verbose_name,
         vertical,
     )
     return super(BaseModelAdmin,
                  self).formfield_for_manytomany(db_field, request,
                                                 **kwargs)
class PlanRelationsForm(forms.Form):
    barrier_plans = forms.ModelMultipleChoiceField(
        BarrierPlan.objects.active(),
        required=False,
        widget=widgets.FilteredSelectMultiple(
            verbose_name=_("Barrier Plans"), is_stacked=False
        ),
    )
    mount_plans = forms.ModelMultipleChoiceField(
        MountPlan.objects.active(),
        required=False,
        widget=widgets.FilteredSelectMultiple(
            verbose_name=_("Mount Plans"), is_stacked=False
        ),
    )
    road_marking_plans = forms.ModelMultipleChoiceField(
        RoadMarkingPlan.objects.active(),
        required=False,
        widget=widgets.FilteredSelectMultiple(
            verbose_name=_("Road Marking Plans"), is_stacked=False
        ),
    )
    signpost_plans = forms.ModelMultipleChoiceField(
        SignpostPlan.objects.active(),
        required=False,
        widget=widgets.FilteredSelectMultiple(
            verbose_name=_("Signpost Plans"), is_stacked=False
        ),
    )
    traffic_light_plans = forms.ModelMultipleChoiceField(
        TrafficLightPlan.objects.active(),
        required=False,
        widget=widgets.FilteredSelectMultiple(
            verbose_name=_("Traffic Light Plans"), is_stacked=False
        ),
    )
    traffic_sign_plans = forms.ModelMultipleChoiceField(
        TrafficSignPlan.objects.active(),
        required=False,
        widget=widgets.FilteredSelectMultiple(
            verbose_name=_("Traffic Sign Plans"), is_stacked=False
        ),
    )
    additional_sign_plans = forms.ModelMultipleChoiceField(
        AdditionalSignPlan.objects.all(),
        required=False,
        widget=widgets.FilteredSelectMultiple(
            verbose_name=_("Additional Sign Plans"), is_stacked=False
        ),
    )

    def __init__(self, *args, **kwargs):
        plan = kwargs.pop("plan")

        super().__init__(*args, **kwargs)

        # Omit instances related to other plans from choices.
        for field_name, field in self.fields.items():
            field.queryset = field.queryset.filter(Q(plan=None) | Q(plan=plan))