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

2022-01-18 00:00:00 python django widget admin forms

问题描述

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

类 ControllerForm(forms.ModelForm):终端 = 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 = "选择要添加到组中的终端."self.fields['terminal'].required = Falseself.fields['terminal'].label = "选择终端"self.fields['terminal'].choices = [(t.id, str(t)) for t in Terminal.objects.filter(associated=False)]元类:模型 = 控制器类 ControllerAdmin(admin.ModelAdmin):"""控制器管理表单自定义."""list_display = ('name', 'group',)表格 = 控制器表格admin.site.register(控制器,ControllerAdmin)

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

解决方案

我已经找到了解决方案.使用 ModelAdmin 中可用的 save_model 方法,可以访问 form.cleaned_data 字典中选择的对象.

def save_model(self, request, obj, form, change):对于 form.cleaned_data['terminal'] 中的终端:...obj.save()

结帐https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model 和 https://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs 了解有关此方法的更多详细信息.p>

谢谢

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)

解决方案

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

相关文章