从Django中的FilteredSelectMultiple小部件中获取所选值

时间:2013-02-05 14:35:36

标签: python django forms widget admin

在Django admin中,有人知道如何在保存表单时从FilteredSelectMultiple小部件中获取所选值吗?

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)

编辑: 我想我可以访问save_model方法中的值。 (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model

3 个答案:

答案 0 :(得分:1)

我已经达成了解决方案。使用ModelAdmin中提供的save_model方法,可以访问form.cleaned_data字典中的所选对象。

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

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

    obj.save()

结帐https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_modelhttps://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs了解有关此方法的更多详情。

由于

答案 1 :(得分: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>

如果您的模板和表单设置如此,则窗口小部件应该发布选择的正确值而不会出现问题。

答案 2 :(得分:0)

参考这个:

这只是使用filteredselectmultiplte小部件

的示例

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