在模板中显示的视图中向表单添加数据

时间:2019-05-02 19:58:57

标签: django django-filter

它将数据从一个视图传输到另一个视图。例如,forwarding=123现在我希望转发显示在我的html模板中,如下例所示。enter image description here

如何将“ forwarding”参数传递给下一个视图的get,以便它在模板中可见并且可以稍后在模板中对其进行编辑??

我的下一个视图

def search(request, forwarding):
    product_list = Product.objects.all().order_by('created')
    product_filter = ProductFilter(request.GET, queryset=product_list) #How can i add here forwarding

    context = {'product_filter': product_filter,}
    return render(request, 'search.html', context)

我的过滤器。py

from .models import Product
import django_filters

class ProductFilter(django_filters.FilterSet):
    title = django_filters.CharFilter(lookup_expr='icontains')
    class Meta:
        model = Product
        fields = ['title']

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找表单的initial参数。

def search(request, forwarding):
    product_list = Product.objects.all().order_by('created')
    initial = {'title': request.GET.get('forwarding')}
    product_filter = ProductFilter(
        request.GET,
        queryset=product_list,
        initial=initial,
    )
    context = {'product_filter': product_filter,}
    return render(request, 'search.html', context)

我没有注意到您使用的是FilterSet。您可以这样覆盖GET数据:

def search(request, forwarding):
    product_list = Product.objects.all().order_by('created')
    data = dict(request.GET)
    if 'title' not in data:
        data['title'] = request.GET.get('forwarding')
    product_filter = ProductFilter(
        data,
        queryset=product_list,
    )
    context = {'product_filter': product_filter,}
    return render(request, 'search.html', context)