tg marcus
tg marcus

Reputation: 167

how to create a dynamic url in python (apiview,django)?

I want to dynamically add an id to an urlpattern and print that id to my server. for example on http://127.0.0.1:8000/experience/3 I want to print 3 to my server.

from django.contrib import admin
from django.urls import path,include
from core.views import TestView
from core.views import ExperienceView
from core.views import ProjectView
from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [

    path('experience/<str:id>', ExperienceView.as_view(),name='experience'),

]
class ExperienceView(APIView):
    ...
    def delete(self,request,*args,**kwargs,id):
        connection = sqlite3.connect('/Users/lambda_school_loaner_182/Documents/job-search-be/jobsearchbe/db.sqlite3')
        cursor = connection.cursor()
        req = request.data
        print(id)
        return Response(data)

Upvotes: 0

Views: 622

Answers (1)

minglyu
minglyu

Reputation: 3327

url parameters are passed to args and kwargs, in this case, you can get your object id from kwargs.

class ExperienceView(APIView):
    ...
    # don't change the signature of delete method
    def delete(self,request,*args,**kwargs):
        # print args and kwargs to see what parameters url passed.
        print(args)
        print(kwargs)
        id = kwargs.get('id')
        return Response(data)

Upvotes: 2

Related Questions