从View中,如何将自定义"选择"传递到表单的ChoiceField中?

Cas*_*per 6 django django-templates django-models django-forms django-views

根据Django docs的说法,ChoiceField接受两个元组的迭代,"或者是一个返回这样一个可迭代的可调用的",用作字段的选择.

ChoiceFields在我的表格中定义了:

class PairRequestForm(forms.Form):
    favorite_choices = forms.ChoiceField(choices=[], widget=RadioSelect, required=False)
Run Code Online (Sandbox Code Playgroud)

这是我试图传递一组自定义选项的视图:

class PairRequestView(FormView):
    form_class = PairRequestForm

    def get_initial(self):
        requester_obj = Profile.objects.get(user__username=self.request.user)
        accepter_obj = Profile.objects.get(user__username=self.kwargs.get("username"))

        # `get_favorites()` is the object's method which returns a tuple.
        favorites_set = requester_obj.get_favorites()

        initial = super(PairRequestView, self).get_initial()

        initial['favorite_choices'] = favorites_set

        return initial
Run Code Online (Sandbox Code Playgroud)

在我的内部models.py,这里是上面使用的返回元组的方法:

def get_favorites(self):
        return (('a', self.fave1), ('b', self.fave2), ('c', self.fave3))
Run Code Online (Sandbox Code Playgroud)

根据我的理解,如果我想预先填充表单,我会通过覆盖传递数据get_initial().我尝试favorite_choices用可调用的方式设置表单的初始数据.可赎回的人favorites_set.

使用当前代码,我收到错误 'tuple' object is not callable

我如何用自己的选择预先填充RadioSelect ChoiceField?

编辑:我也尝试过设置 initial['favorite_choices'].choices = favorites_set

Clé*_*oix 7

get_initial方法用于填充表单字段的初始值。不要设置可用choices或修改您的字段属性。

要成功地将您的选择从您的视图传递到表单,您需要get_form_kwargs在您的视图中实现该方法:

class PairRequestView(FormView):
    form_class = PairRequestForm

    def get_form_kwargs(self):
        """Passing the `choices` from your view to the form __init__ method"""

        kwargs = super().get_form_kwargs()

        # Here you can pass additional kwargs arguments to the form.
        kwargs['favorite_choices'] = [('choice_value', 'choice_label')]

        return kwargs
Run Code Online (Sandbox Code Playgroud)

在您的表单中,从方法中的 kwargs 参数中__init__获取选择并在字段上设置选择:

class PairRequestForm(forms.Form):

    favorite_choices = forms.ChoiceField(choices=[], widget=RadioSelect, required=False)

    def __init__(self, *args, **kwargs):
        """Populating the choices of  the favorite_choices field using the favorites_choices kwargs"""

        favorites_choices = kwargs.pop('favorite_choices')

        super().__init__(*args, **kwargs)

        self.fields['favorite_choices'].choices = favorites_choices
Run Code Online (Sandbox Code Playgroud)

瞧!


jav*_*ved 5

另一种简单的方法是:

class PairRequestView(FormView):
    form_class = PairRequestForm

    def get_form(self, *args, **kwargs):
         requester_obj = Profile.objects.get(user__username=self.request.user)
         favorites_set = requester_obj.get_favorites()
         form = super().get_form(*args, **kwargs)
         form.fields['favorite_choices'].choices = favorites_set
         return form
Run Code Online (Sandbox Code Playgroud)