需要触发接受Django表单的文本字段值作为参数

问题描述 投票:0回答:1

我是Django的新手。我有一个脚本,我计划制作一个Web APP。我需要将一些值通过HTML表单操作方法传递到我的python脚本中。并且脚本输出显示在同一页面或不同页面中。示例脚本:

a={{get-val1-from form}}
b={{get-val2-from-form}}
def add(a,b):
    return (a+b)

我的HTML表单如下所示:

<form action="/">
  <fieldset>
    <legend>Input Requirements<br></legend>
    <p>
      <label>Value A:<br></label>
      <input type="text" name="val1" value="">
    </p>
    <p>
      <label>Value B:<br></label>
       <input type="text" name="val2" value="">
    </p>
    <p>
      <button id="Submit" > Analyze
             </button>
    </p>       
    <p>
      <label>Result : <br></label>
      <textarea id="out_string"> {{out_string}}
      </textarea>
  </fieldset>
</form>

我想通过Django实现它,请让我知道使用视图模板的方法。提前致谢..

python django python-3.x django-forms django-templates
1个回答
0
投票

在urls.py中定义要从用户发送输入的路径。例

from app_name import views
path('answer/', views.answer, name = "ans_url"),

然后在app_name / views.py中定义视图,如下所示

def answer (request):
    if request.method == 'POST':
        form = form_name (request.POST)
        if form.is_valid():
            a = form.cleaned_data['A']
            b = form.cleaned_data['B']
            ans = your_function(a, b)
            return render (request, 'ans_template.html', {'ans' : ans})
    else :
        form = form_name()
    return render (request, 'your_template.html', {'form' : form})

def your_function (a, b):
    #Process
    return (a+b)

然后在your_template.html中,您可以按如下方式定义表单

<form action="{% url 'ans_url' %}" method='POST'>
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Analyze">
</form>

如果您仍然感到困惑,最好一次阅读文档。这里解释得很漂亮。 https://docs.djangoproject.com/en/2.0/topics/forms/

© www.soinside.com 2019 - 2024. All rights reserved.