0

I am working on APIs using django. I want to access my resources in following way: {base_url}/employee/{emp_id}.

Here emp_id is not a GET parameter. How can I access this parameter in my view? Is there any standard way to access it without manually parsing URL?

3
  • 2
    Have you read the documentation on the URL dispatcher? That's a great start that explains this in detail. Commented Apr 15, 2015 at 22:26
  • That is good link! Thanks! Does this mean that I need to write different functions to handle different requests? Commented Apr 15, 2015 at 22:29
  • 1
    That's generally how it's done, unless handling different requests is essentially the same save a few parameters. It's easy to map different url patterns to a single view function. Commented Apr 15, 2015 at 22:33

1 Answer 1

1

Depending on whether you are using class based views or whether you are using standard view functions the method is different.

For class based views, depending on which action you are willing to perform (ListView, DetailView, ...) usually you do not need to parse the url but only to specify the name of the argument in your urls.py or the name of the argument directly inside the class definition.

Class based views

urls.py

from mysite.employee.views import EmployeeView

urlpatterns = patterns('',
    ...
    url(r'^employee/(?P<pk>[\d]+)/$', EmployeeView.as_view(), name='employee-detail'),
    ...
)

employee/views.py

class EmployeeView(DetailView):
    model = YourEmployeeModel
    template_name = 'employee/detail.html'

Please read the doc that knbk pointed out to you as you need to import DetailView

And as simply as that, you will get your employee depending on the pk argument given. If it does not exist a 404 error will be thrown.


In function based views it is done in a similar way:

urls.py

from mysite.employee.views import EmployeeView

urlpatterns = patterns('',
    ...
    url(r'^employee/(?P<pk>[\d]+)/$', 'mysite.employee.views.employee_detail', name='employee-detail'),
    ...
)

employee/views.py

from django.shortcuts import get_object_or_404

def employee_detail(request, pk):
""" the name of the argument in the function is the 
    name of the regex group in the urls.py
    here: 'pk'
"""
    employee = get_object_or_404(YourEmployeeModel, pk=pk)

    # here you can replace this by anything
    return HttpResponse(employee)

I hope this helps

Sign up to request clarification or add additional context in comments.

1 Comment

Does this answer your question? Mark solved if it does please

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.