简体   繁体   English

将参数从模板传递到Django中的视图

[英]Passing parameter from template to view in Django

A Django noob here. 这里是Django的菜鸟。 I'm stuck with my problem regarding exporting csv in django. 我对在django中导出csv的问题感到困惑。 I'm currently successfully exporting a csv file containing all the objects(Product) in the database using this function in views.py of my Model Product. 我目前正在使用我的模型产品的views.py中的此函数成功导出包含数据库中所有对象(产品)的csv文件。

def export_csv(request):

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="product-inventory.csv"'

    writer = csv.writer(response)
    writer.writerow(['Product Name', 'STATUS'])

    products = Product.objects.all().values_list('name', 'status')

    for product in products:
        writer.writerow(product)

    return response

This is in my template 这是在我的模板中

<a class="export-btn" id="test" href="{% url 'export_csv' %}">Export</a>

And this is the url.py 这是url.py

url(r'^export/csv$', product_views.export_csv, name='export_csv')

The question is how can I change dynamically the Product.objects.all() in my export_csv function so that it will be equal to the product list obtained from the user using search (using request.GET in another function)? 问题是如何动态更改export_csv函数中的Product.objects.all() ,使其等于使用搜索(在另一个函数中使用request.GET)从用户那里获得的产品列表?

Thanks in advance. 提前致谢。

Try to add in template form: 尝试添加模板形式:

<form method="GET" action="">
     <input type="text"  name="q" placeholder="Search">
     <input type="submit" value="Search">
 </form>

Now in view you can get search value and filter products: 现在,您可以获取搜索值并过滤产品:

search = request.GET.get('q')
products = Product.objects.filter(name__icontains=search).values_list('name', 'status')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM