Home > Software design >  How to get data from url in django without query parameters
How to get data from url in django without query parameters

Time:07-31

sorry for my noob question as I am just starting to learn Django. I would appreciate if someone could tell me how can i change data dynamically on page in django. Let me clear this:

What I want:

When url is http://localhost/data/1111, page data should be like data is 1111.

When url is http://localhost/data/2222, page data should be like data is 2222.

What I did:

def index(request):
    print(int(request.GET["data"]))          # for debugging only
    return HttpResponse("data of Page")

and url was:

path('<int:data>', views.index, name='index')

CodePudding user response:

Since you have a value in your url, the <int:data> part, that needs to be captured by the view, which means your view function has to be aware of the extra parameter.

So, the correct view for this would be:

def index(request, data):
    print(data)  # data is already converted to int, since thats what you used in your url
    return HttpResponse(f"data is {data}")

CodePudding user response:

Since you don't want to pass query parameters in your url, change your url to look like this

path('data/', views.index, name='index')

def index(request):
   print(int(request.GET["data"])) # for debugging only
   return HttpResponse("data of Page")

Note that on GET['data'], data is not what is on the url pattern but rather it should be a input name on the form like <input name='amount' type='number' />

Now you can access amount like this

def index(request):
   print(int(request.GET["amount"])) # for debugging only
   return HttpResponse("data of Page")
  • Related