[英]Decide value from django template 'int' or 'str'
我在Django模板中有一個表單。 在從此表單獲取數據的視圖中,我需要檢查條目是'str'還是'int'。 如果是'str',我必須提出一個錯誤。 但是當我使用以下方法檢查條目的類型時:
pr = request.GET['pr no']
print "Type of PR:%s" % type(pr)
無論'pr'是字符串還是整數,type()函數都將返回'unicode'。 我該怎么辦呢? 謝謝
好吧,顯然.GET['pr no']
總是返回一個Unicode
對象。
該字符串是否包含整數可以進行測試:
if pr.isdigit(): # ASCII digits
要么
if pr.isnumeric(): # also Unicode digits
或者,你可以做
try:
int(pr)
except ValueError:
print "PR is not an integer"
或檢查任何有效數字:
try:
float(pr)
except ValueError:
print "PR is not a number"
以html格式,文本輸入框用於輸入整數值。 因此,您在python視圖中獲得的值將始終是unicode字符串。
要實現您想要的功能,可以使用unicode字符串的.isdigit()
方法進行測試。
例:
>>> x=u'99A'
>>> x.isdigit()
False
>>> x=u'99'
>>> x.isdigit()
True
>>>
>>> x=u'A99'
>>> x.isdigit()
False
>>>
如果使用的是django表單,則可能要使用適當的表單字段(可能是IntegerField
)並驗證表單以獲取錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.