[Fixed]-Using regex on Charfield in Django

0👍

Regex are great, but sometimes it is more simpler and readable to use other approaches. For example, How about just using builtin types to check for the type

try:
    att_name = float(att.name)
    ret = "Integer" if att_name.is_integer() else "Float"
except ValueError:
    ret = "String"

FYI, your regex code works perfectly fine. You might want to inspect the data that is being checked.

Demo:

>>> import re
>>> a = re.compile('^\d+$')
>>> b = re.compile('^\d+\.\d+$')
>>> a.match('10')
<_sre.SRE_Match object at 0x10fe7eb28>
>>> a.match('10.94')
>>> b.match('10')
>>> b.match('10.94')
<_sre.SRE_Match object at 0x10fe7eb90>
>>> a.match("string")
>>> b.match("string")

1👍

You can try with RegexValidator

Or you can to it with package django-regex-field, but i would rather recommand you to use built-in solution, the less third-party-apps the better.

Leave a comment