djangodjango-urls

Django urls uuid not working


In the following, if the url is set as ,what should be the pattern for uuid?

urls.py

url(r'^getbyempid/(?P<emp_id>[0-9]+)/(?P<factory_id>[0-9]+)$',views.empdetails)

Doesnt work,

http://10.0.3.79:8000/app1/getbyempid/1/b9caf199-26c2-4027-b39f-5d0693421506

but this works

http://10.0.3.79:8000/app1/getbyempid/1/2

Solution

  • As well as the digits 0-9, the uuid can also include digits a-f and hyphens, so you could should change the pattern to

    (?P<factory_id>[0-9a-f-]+)
    

    You could have a more strict regex, but it's not usually worth it. In your view you can do something like:

    try:
        factory = get_object_or_404(Factory, id=factory_id)
    except ValueError:
        raise Http404
    

    which will handle invalid uuids or uuids that do not exist in the database.