【问题标题】:Get the value of input text element after pressing submit button in django在django中按下提交按钮后获取输入文本元素的值
【发布时间】:2017-09-11 11:42:03
【问题描述】:

我是 Django 的新手,上周开始学习它。我的问题是我有一个网页,它有一个输入文本框和一个提交按钮。 我要捕获在Django中按下提交按钮后在文本框中输入的下一个网页(重定向页面)中输入的输入字符串

我尝试了以下方法:

views.py

#View for the initial page
def index(request):
    return render( request, 'index.html')

#View for the Redirecting page -- This is where I want to catch the text box input
def results(request):
    inp_value = request.GET.get('text_search', 'This is a default value')
    context = {'inp_value': inp_value}
    return render( request, 'results.html', context)

forms.py

from django import forms

class TextForm(forms.Form):
    text_search = forms.CharField(label='Text Search', max_length=100)

index.html

<form action="/searcher/results/" method="get">
        <label for="results">Enter a string: </label>
        <input id="results" type="text" name="results" value="{{ search_results }}">
        <input type="submit" value="submit">
    </form> 

谁能指出为什么我无法获得文本框的值?

提前致谢

【问题讨论】:

    标签: python html django


    【解决方案1】:

    request.GET 键是输入的名称。因此,在您的情况下,既然您想要 &lt;input type="text" name="results"&gt; 的值,您应该从 request.GET.get('results') 获取该值。

    但是,还有一个 {{ search_results }} 值不会从您的 index 视图中呈现。因此,它将始终为空。

    def results(request):
        inp_value = request.GET.get('results', 'This is a default value')
        context = {'inp_value': inp_value}
        return render( request, 'results.html', context)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      相关资源
      最近更新 更多