Santhosh
Santhosh

Reputation: 11774

Django: pass some paremeter to view in Django urls

I want to pass some string for some urls to my views in django

Suppose i have

path('someurl/', someview , name='someurl'),

I want to pass some string to someview, when this url is called so is this possible

path('someurl/', someview(somevar="test") , name='someurl'),

and then i have the view

def someview(request, somevar):
    access somevar here

Is this possible in Django urls.

Upvotes: 3

Views: 1776

Answers (2)

Elgin Cahangirov
Elgin Cahangirov

Reputation: 2022

If you wish to accept parameter from the client, update your path as below:

path('someurl/<str:somevar>/', someview , name='someurl')

And view now can accept extra parameter:

def someview(request, somevar):
    # now you can use somevar

With this definition, if client requests somevar/urlparam/, "urlparam" will be passed to you view function.

Otherwise if you want to provide your own argument, Django doesn't provide the way to do it directly in url definition. But, since that variable is your own one, why don't assign (or compute) that in view? I mean:

def someview(request):
    somevar = "test"  # or you may call some function for dynamic assignment
    # now somevar exists in this scope, so you can use it as you want

Upvotes: 4

tstoev
tstoev

Reputation: 1435

yes it is possible. You need to define those parameters in the url as pseudo path:

path('articles/<int:year>/<int:month>/', views.month_archive),

There is also an option to use request.GET and request.POST to access the optional parameters list in the url:

 request.POST.get('<par name here>','<default value here>')
 request.GET.get('<par name here>','<default value here>')

Another thing you may find useful is this question.

Upvotes: 0

Related Questions