Get the chosen values from FilteredSelectMultiple widget in Django

浪尽此生 提交于 2020-02-01 09:39:14

问题


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)


回答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




回答2:


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.




回答3:


Refer to this one:

This is only example using filteredselectmultiplte widget

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



来源:https://stackoverflow.com/questions/14709973/get-the-chosen-values-from-filteredselectmultiple-widget-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!