[Django]-How to pass url value in django to views

3👍

Change your urls.py to

from myapp import views
urlpatterns = [
       url(r'^myapp/get_requests/(?P<id>[0-9]+)$', views.get_requests),
]

Now get the id parameter in your views like this

@api_view(['GET'])
def get_request(request,id):
    print id
    return HttpResponse('test')

For more information check out django docs

1👍

If you want to pick up id from url, you just have to write something like this :

@login_required
def MyFunction(request, id) :

    myobject = get_object_or_404(MyModel, pk=id)

    context = {
            "myobject" : myobject,
    }

    return render(request, 'my template.html', context)

And your url, you have to add url(r'^myapp/get_requests/(?P<id>\d+)/$', views.get_requests),

I assume your url is correct and he’s already created with id inside. So I just gave you How I pick up object according to this ID.

👤Essex

0👍

There is a typo in the view function name in your above code. So, it would be get_requests not get_request.

Now coming to your question, it throws you 404 - Not Found because there is no actual route that you’ve defined that should expect the id after the url.

To start accepting id, add another route for it in your urls.py which has a digit regext like:

from myapp import views
urlpatterns = [
   url(r'^myapp/get_requests/$', views.get_requests),
   url(r'^myapp/get_requests/(?P<id>\d+)$', views.get_requests_with_id),
]

and in your views.py, define the view function to accept id parameter something like this:

@api_view(['GET'])
def get_requests_with_id(request, id):
   # Now use id for whatever you want
   return HttpResponse('test')

You can read about it form the official documentation here: https://docs.djangoproject.com/en/1.11/topics/http/urls/#named-groups

Leave a comment