django表单不会使用实例

时间:2016-11-10 20:21:34

标签: python django

我有以下表格:

class SearchDetailForm(forms.ModelForm):
    price_min = forms.DecimalField(max_digits=8, decimal_places=2, required=False)
    price_max = forms.DecimalField(max_digits=8, decimal_places=2, required=False)
    item = forms.ModelChoiceField(queryset=Item.objects.all(), required=False)
    max_distance = forms.CharField(required=False)
    sort = forms.ChoiceField(choices=SORT_CHOICES)

    class Meta:
        model = Buy
        fields = (
                  'item',
                  'max_distance',
                  'price_min',
                  'price_max'
                  )

实现此表单的视图如下所示:

def market_view(request):

    max_distance = request.GET.get('max_distance',None)
    price_min_str = request.GET.get('price_min',None)
    price_max_str = request.GET.get('price_max',None)
    price_min = Decimal(price_min_str)
    price_max = Decimal(price_max_str)
    item = request.GET.get('item',None)

    buy = Buy()
    buy.price_min = Decimal('10.10')
    buy.price_max = Decimal('10.10')
    buy.item = Item.objects.get(pk=item)

    buy_items = Buy.objects.filter(price__lte=price_max,price__gte=price_min).order_by('item')

    form = SearchDetailForm(instance=buy)

    context = {
        'items':buy_items,
        'form':form,

    }

    return render(request, 'index.html', context)

我将表单实例设置为buy,以便最后搜索的值保留在页面上。 item属性仍然存在,但price_minprice_max没有。我可以让他们做什么来填充表单实例?

0 个答案:

没有答案