當前位置:成語大全網 - 新華字典 - web的get請求中壹個key有多個值的情況django是怎麽處理的

web的get請求中壹個key有多個值的情況django是怎麽處理的

在HttpRequest對象中, GET和POST屬性是django.http.QueryDict類的實例。 QueryDict類似字典的自定義類,用來處理單鍵對應多值的情況。因為壹些HTML form元素,例如,<selectmultiple="multiple">, 就會傳多個值給單個鍵。

QueryDict對象是immutable(不可更改的),除非創建它們的copy()。這意味著我們不能直接改變request.POST and request.GET的屬性。

QueryDict實現所有標準的字典方法。還包括壹些特有的方法,見Table H-3.

A Complete Example

例如, 下面是壹個HTML form:

<form action="/foo/bar/" method="post">

<input type="text" name="your_name" />

<select multiple="multiple" name="bands">?

<option value="beatles">The Beatles</option>

<option value="who">The Who</option>

<option value="zombies">The Zombies</option>

</select>

<input type="submit" />

</form>

如果用戶在your_name域中輸入"JohnSmith",同時在多選框中選擇了“The Beatles”和“The Zombies”,下面是Django請求對象的內容:

>>> request.GET{}

>>> request.POST

{'your_name': ['John Smith'], 'bands': ['beatles', 'zombies']}

>>> request.POST['your_name']

'John Smith'?

>>> request.POST['bands']

'zombies'

>>> request.POST.getlist('bands')

['beatles', 'zombies']

>>> request.POST.get('your_name', 'Adrian')

'John Smith'

>>> request.POST.get('nonexistent_field', 'Nowhere Man')

'Nowhere Man'

HttpResponse

對於HttpRequest 對象來說,是由Django自動創建, 但是,HttpResponse對象就必須我們自己創建。每個View方法必須返回壹個HttpResponse對象。

HttpResponse類在django.http.HttpResponse。