2017-04-15 46 views
0

我是Django的新手,並在上週開始學習它。我的問題是我有一個網頁,其中有一個輸入文本框和一個提交按鈕。 我想捕獲在按下Django中的提交按鈕後在文本框中輸入的下一個網頁(重定向頁面)中輸入的輸入字符串在django按提交按鈕後獲取輸入文本元素的值

This is how the initial web page looks like

我曾嘗試以下:

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> 

任何人都可以指出爲什麼我不能得到文本框的值?

由於提前

回答

0

request.GET鍵是輸入的名稱。所以,在你的情況下,因爲你想要<input type="text" name="results">的值,你應該從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) 
+0

謝謝,nik_m工作! –