1

在 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

4

3 回答 3

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 有关此方法的更多详细信息。

谢谢

于 2013-02-06T12:03:10.347 回答
0

表格.py

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

我的寺庙.html

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

如果您有这样的模板和表单设置,小部件应该毫无问题地发布正确的值。

于 2013-02-05T14:44:07.033 回答
0

参考这个:

这只是使用filteredselectmultiplte 小部件的示例

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

于 2013-02-05T14:45:37.720 回答