0

I have an existing Django application. I need to include a functionality in it which doesn't involve DB. I have written the operation to be performed in views.py

 class VamComponent(View):
    def getSectionADetails(self,request):
     .......
    return HttpResponse()

In urls.py I have included this line in urlpatterens:

url(r'^vamcomponent$', VamComponent.as_view())

I am able to access the details from this url http://localhost:8000/vamcomponent/ .

I need to have my endpoints with some value for section in the url like http://localhost:8000/vamcomponent/SectionA and http://localhost:8000/vamcomponent/SectionB.

In views.py if I modify the class to have 2 functions it,based on the value of section in the request it should call the respective method

 class VamComponent(View):
    def getSectionADetails(self,request):
     .......
    return HttpResponse()
    def getSectionBDetails(self,request):
     .......
    return HttpResponse()

How to make this change in urls.py file so that getSectionADetails() is called when the request has SectionA in it else getSectionBDetails()?

1 Answer 1

3

I think you can try like this:

First, you need to update the view so that it accepts a new parameter, ie SectionA or SectionB # urls

url(r'^vamcomponent/(?P<section>[-\w]+)/?$', VamComponent.as_view())

Now lets update the view accordingly, so that the value passed in urls goes to the view:

class VamComponent(View):
     def get(self, request, section=None):  # or post if necessary
         if section == "SectionB":
            return self.getSectionBDetails(request)
         return self.getSectionADetails(request)    

FYI, if you are using django-rest-framework, then why don't you use APIView:

from rest_framework.views import APIView

class VamComponent(APIView):
    # rest of the code
Sign up to request clarification or add additional context in comments.

2 Comments

If I use APIView, do I need to use the same url patterns as I do the View?
@Jayashree Yes, also it will allow you to use some functionalities such as permissions_classes,authentication_classes etc. More information are provided in documentation(attached with the answer)

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.