Django:动态IntegerField初始化(渲染为空)

时间:2012-07-13 08:25:10

标签: django forms

我需要一个整数表单字段来获得'default'值。但是我需要在运行时定义这个值。

我这样做:

# at my form constructor:
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList,
             label_suffix=':', empty_permitted=False):
    super(FlatSearchForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix,
        empty_permitted)

    min_price = ... # some code to find the minimum price
    self.price_min = min_price # will be used later

    max_price = ... # some code to find the maximum price
    self.price_max = max_price

    # here we go:
    self.fields['price_from'] = forms.IntegerField(min_value=min_price, max_value=max_price, initial=min_price)
    self.fields['price_to'] = forms.IntegerField(min_value=min_price, max_value=max_price, initial=max_price)

# ...
# how I use the form (in views.py):
class SearchFlatView(ListView):
    model = Flat
    context_object_name = 'flats'
    template_name = 'catalog/search.html'

    def get_context_data(self, **kwargs):
        context = super(SearchFlatView, self).get_context_data(**kwargs)
        context['form'] = FlatSearchForm(self.request.GET)
        return context

问题是:当我使用{{form.price_from}}和{{form.price_to}}呈现字段时,表单中不显示值 - 这些字段只是空的!

你能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:1)

您无法为绑定表单中的字段设置动态初始值。请参阅文档:https://docs.djangoproject.com/en/dev/ref/forms/fields/#initial

  

初始参数允许您指定要使用的初始值   以未绑定的形式呈现此字段。

然而,你可以做的是创建一个未绑定的表单,同时仍保留请求.GET参数:

initial = request.GET.copy()
initial['price_from'] = some_min_price
initial['price_to'] = some_max_price
context['form'] = FlatSearchForm(initial=initial)

在__iniit__形式中,您将拥有:

def __init__(self, *args, **kwargs):
    super(Form, self).__init__(*args, **kwargs)
    initial = kwargs.get("initial", {})
    default_min_value = ... #  some default value in case there is no `initial` passed
    default_max_value = ...
    self.fields['price_from'] = forms.IntegerField(min_value=initial.get('min_value', default_min_value), max_value=initial.get('max_value', default_max_value))
    self.fields['price_to'] = forms.IntegerField(min_value=initial.get('min_value', default_min_value), max_value=initial.get('max_value', default_max_value))

或者,如果需要,您可能想要更改此逻辑。