Converting GET request parameter to int ... if it is numeric
<p>lets say i'm showing some data to user  , i want user to be able to perform some sort of filtering on a numeric field in the database  using a <code>GET</code> form so i have something like this </p>

<pre><code>code = request.GET.get('code')
condition = {} 
if( code is not None and int(code) &gt; 0 ):
  condition['code'] = int(code)

Somemodel.objects.filter(**condition)
</code></pre>

<p>but this works only if i code contains a number otherwise i get  this error </p>

<pre><code>invalid literal for int() with base 10: ''
</code></pre>

<p>so what is the pythonic way to handle this problem ? should i use <code>try/except</code> block? i perfer to handle this in the same <code>if</code> statement considering i might add other filters </p>

<p>You should use a Django form with one or more IntegerFields; they do this conversion for you, then you can get the result from <code>cleaned_data</code>.</p>

python django python-3.x django-1.9