将多个值从用户输入传递到Django视图

将多个值从用户输入传递到Django视图

本文介绍了将多个值从用户输入传递到Django视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我理解Django工作的方式。

从浏览器的地址栏中搜索urls.py以获取匹配的地址。
如果找到地址,下一步是访问views.py
中的def()。def()会将数据返回到网页。



我想做什么,不了解这样做的机制是从网页上输入两个输入日期并将其传递给views.def()。在网页上提交更多的数据输入。如果是这样,这是如何工作的?



test.html

  {%extends'base.html'%} 
{%block content%}
< br />< br />
< form action =method =get>
< label for =from>起始日期< / label>
< input type =textname =start_date>< br />< br />
< label for =to>结束日期& nbsp;< / label>
< input type =textname =end_date>< br />
< input type =submitvalue =Submit>
< / form>
< p> {{s_date}}< / p>
< p> {{e_date}}< / p>
{%endblock%}

views.py p>

  def Test(request):
if'start_date'in request.GET:
s_date = request.GET ['start_date']
e_date = request.GET ['end_date']
else:
s_date =无
e_date =无
上下文= {s_date: s_date,e_date:e_date}
return render_to_response('test.html',context,context_instance = RequestContext(request))

在Stackoverflow消息中使用了method =post。因为我只想读取数据将method =get更好?



以防万一,日期以yyyy-mm-dd格式存储。 p>

该功能正在运行。我想知道关于将变量从模板传递给函数的错误。



谢谢。

解决方案

您可以使用,例如 request.GET ['start_date'] request.GET ['end_date']


This is as I understand the way Django works.
From the address bar in the browser the urls.py is searched for a matching address.If address is found the next step is access a def() in the views.pyThe def() does stuff and passes data back to the web page.

What I want to do, and failing to understand the mechanism to do so, is to take two input dates from the web page and pass them to the views.def(). Does submit on the web page store more that one data entry. If so, how does this work?

test.html

{% extends 'base.html' %}
{% block content %}
    <br /><br />
    <form action="" method="get">
        <label for="from">Start Date</label>
            <input type="text" name="start_date"><br /><br />
        <label for="to">End Date &nbsp;</label>
            <input type="text" name="end_date"><br />
        <input type="submit" value="Submit">
    </form>
    <p>{{ s_date }}</p>
    <p>{{ e_date }}</p>
{% endblock %}

views.py

def Test(request):
    if 'start_date' in request.GET:
        s_date = request.GET['start_date']
        e_date = request.GET['end_date']
    else:
        s_date = None
        e_date = None
    context = {"s_date": s_date, "e_date": e_date}
    return render_to_response('test.html', context, context_instance=RequestContext(request))

On the Stackoverflow message Passing objects from template to view using Django method="post" is used. As I only want to read the data would method="get" be better?

Just in case, the dates are stores in yyyy-mm-dd format.

The function is working. I would like to know what I am missing regarding the passing of the variables from template to function.

Thank you.

解决方案

You can access GET parmeters using request.GET, for example request.GET['start_date'] and request.GET['end_date'].

这篇关于将多个值从用户输入传递到Django视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 03:55