Core_Dumped
Core_Dumped

Reputation: 4719

Decide value from django template 'int' or 'str'

I have a form in django template. In the view that gets data from this form, I need to check if the entry is 'str' or 'int'. If it's 'str', I have to raise an error. But when I check the type of the entry by using:

pr = request.GET['pr no']
print "Type of PR:%s" % type(pr)

irrespective of the 'pr' being string or integer, type() function returns 'unicode'. How do I go about it? Thanks

Upvotes: 2

Views: 3002

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

Well, obviously .GET['pr no'] always returns a Unicode object then.

Whether that string contains an integer can be tested:

if pr.isdigit():   # ASCII digits

or

if pr.isnumeric(): # also Unicode digits

Alternatively, you could do

try:
    int(pr)
except ValueError:
    print "PR is not an integer"

or check for any valid number:

try:
    float(pr)
except ValueError:
    print "PR is not a number"

Upvotes: 6

Rohan
Rohan

Reputation: 53386

In html form, text input box is used to input integer values. So values you get in python view for it will always be unicode string.

To achieve what you want to do, you can test with .isdigit() method of unicode string.

Example:

>>> x=u'99A'
>>> x.isdigit()
False
>>> x=u'99'
>>> x.isdigit()
True
>>> 
>>> x=u'A99'
>>> x.isdigit()
False
>>> 

If you are using django form, you may want to use appropriate form field (likely IntegerField ) and validate the form to get errors.

Upvotes: 1

Related Questions