1

In Django admin , does anyone know how can i get the chosen values from FilteredSelectMultiple widget in, when the form is saved?

class ControllerForm(forms.ModelForm):
terminal = forms.ModelMultipleChoiceField(queryset=[])

    def __init__(self, *args, **kwargs):
        super(ControllerForm, self).__init__(*args, **kwargs)
        self.fields['terminal'].widget = widgets.FilteredSelectMultiple('terminals', False)
        self.fields['terminal'].help_text = "Select the terminals which are to be added to the group."
        self.fields['terminal'].required = False
        self.fields['terminal'].label = "Select terminal(s)"
        self.fields['terminal'].choices = [(t.id, str(t)) for t in Terminal.objects.filter(associated=False)]
    class Meta:
        model = Controller
class ControllerAdmin(admin.ModelAdmin):
    """
    Controller admin form customization.
    """
    list_display = ('name', 'group',)

    form = ControllerForm

admin.site.register(Controller, ControllerAdmin)

EDIT: I think i can access the values in the save_model method. (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model)

luistm
  • 1,027
  • 4
  • 18
  • 43

3 Answers3

1

I've reached a solution. Using the save_model method available in the ModelAdmin one can access the chosen objects in the form.cleaned_data dictionary.

def save_model(self, request, obj, form, change):

    for terminal in form.cleaned_data['terminal']:
        ...

    obj.save()

Checkout https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model and https://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs for more details on this method.

Thanks

luistm
  • 1,027
  • 4
  • 18
  • 43
0

forms.py

class SampleWidget(forms.Form):
    date=forms.CharField(widget=AdminDateWidget,max_length=100)
    users = forms.ModelMultipleChoiceField(queryset=User.objects.all(),widget=FilteredSelectMultiple(("Users"), False))

mytemple.html

<form action="." method="POST">
{{ form.as_p }}
{{ form.media }}
{% csrf_token %}
<p><input type="submit" value="Submit"></p>
</form>

The widget should post the correct values selected without issue if you have your templates and forms setup like so.

Mahdi Yusuf
  • 19,931
  • 26
  • 72
  • 101
0

Refer to this one:

This is only example using filteredselectmultiplte widget

http://jayapal-d.blogspot.com/2009/08/reuse-django-admin-filteredselectmultip.html

catherine
  • 22,492
  • 12
  • 61
  • 85