[Answer]-How to access url part in python django?

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

Leave a comment