我正在嘗試使用以下代碼將模板中的值轉換為視圖:
<form action="{% url 'view_passwordgenerator' %}">
<select name="length">
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12" selected="selected">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
</select> Length
<input type="submit" value="Generate Password" class="btn btn-primary">
</form>```
意見
def view_passwordgenerator(request):
length = int(request.GET.get('length'))
for i in range(length):
...
return render(request, 'home/passwordgenerator.html')
出現此錯誤:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
我只是在尋找一種方法可以在沒有此錯誤的情況下從模板中獲取 int,也許還有另一種方法可以轉換它。
uj5u.com熱心網友回復:
當使用相同的視圖提交表單時,您可能會同時渲染帶有表單的頁面和帶有結果的頁面。
因此,當您第一次渲染該視圖時,length將丟失,因此您應該檢查并僅int在我們知道它是字典的一部分時才將其轉換為 an :
def view_passwordgenerator(request):
if 'length' in request.GET:
length = int(request.GET.get('length'))
for i in range(length):
# …
return render(request, 'home/passwordgenerator.html')
return …
然而,這仍然非常優雅,因為人們可以使用 URL 將資料注入到 中request.GET,而這本身并不是一個整數。最優雅的方式可能是使用 Django 表單:
from django import forms
class MyForm(forms.Form):
length = forms.IntegerField()
然后您可以檢查表單是否驗證:
def view_passwordgenerator(request):
form = MyForm(request.GET)
if form.is_valid():
for i in range(form.cleaned_data['length']):
# …
return render(request, 'home/passwordgenerator.html')
return …
您可以通過將所選專案傳遞給背景關系來呈現它:
def view_passwordgenerator(request):
if 'length' in request.GET:
length = int(request.GET.get('length'))
for i in range(length):
# …
return render(request, 'home/passwordgenerator.html', {'length': length})
return …
然后用:
<select name="length">
<option value="8" {% if length == 8 %}selected{% endif %}>8</option>
<option value="9" {% if length == 9 %}selected{% endif %}>9</option>
<option value="10" {% if length == 10 %}selected{% endif %}>10</option>
<option value="11" {% if length == 11 %}selected{% endif %}>11</option>
<option value="12" {% if length == 12 %}selected{% endif %}>12</option>
<option value="13" {% if length == 13 %}selected{% endif %}>13</option>
<option value="14" {% if length == 14 %}selected{% endif %}>14</option>
<option value="15" {% if length == 15 %}selected{% endif %}>15</option>
<option value="16" {% if length == 16 %}selected{% endif %}>16</option>
<option value="17" {% if length == 17 %}selected{% endif %}>17</option>
<option value="18" {% if length == 18 %}selected{% endif %}>18</option>
<option value="19" {% if length == 19 %}selected{% endif %}>19</option>
<option value="20" {% if length == 20 %}selected{% endif %}>20</option>
</select>
但是,我建議使用這些可用于呈現、驗證和清理資料的表單。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/327174.html
