Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django urls uuid not working

Tags:

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 
like image 865
Rajeev Avatar asked Oct 05 '15 13:10

Rajeev


People also ask

How can we handle urls in Django?

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).

What is Re_path in Django?

re_path is a callable within the django. urls module of the Django project.

How do I change the default URL in Django?

Set up app folder's urls.py and html files In the same directory, you should have a file named views.py. We will create a function called index which is what makes the http request for our website to be loaded. Now, we've set it up such that http://127.0.0.1:8000/homepage will render the HTML template index.


2 Answers

Since Django 2.0 you don't even need to worry about regex for UUID and int with new Django feature: Path Converters.

Make code elegant again:

from django.urls import path ...  urlpatterns = [     ...     path('getbyempid/<int:emp_id>/<uuid:factory_id>', views.empdetails) ] 
like image 148
vishes_shell Avatar answered Sep 24 '22 19:09

vishes_shell


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.

like image 45
Alasdair Avatar answered Sep 23 '22 19:09

Alasdair