Home > OS >  Passing Two Parameters Through URL in Django
Passing Two Parameters Through URL in Django

Time:10-21

I'm having difficulty passing parameters to a URL in Django.

I am attempting to pass two parameters from calander.html -> succ.html. The URL looks like this: Click for Image of URL

In that image I want to pass 11:00am as the Start Time and 12:00pm as the end Time.

My urls.py file contains:

path('calender', views.calender, name='calender'),
....
....
path('succ', views.succ, name='succ'),

My views.py file contatins:

def calender(request):
return render(request, 'calender.html')

def succ(request):
return render(request, 'succ.html')

I attempted to add parameters to the views.py file and then add a new path in urls.py after watching several videos and I was never able to find a solution since I am passing two parameters (StartTime and EndTime).

CodePudding user response:

Note: Colons : are invalid for urls, use underscores _ instead and do a start = start.replace('_', ':') in the view if you really need the colon

I'm not sure if that was your only issue you were running into, but here's two broken down ways you can pass parameters to a view. They both essentially do the same thing

1 Using Django URLs

## Urls
# Notes:
#   both point at the same view (See next section)
#   <slug> means it's a string

path('calender', views.calender, name='calender'),

path('calender/<slug:StartDate>/<slug:EndDate>', views.calender, name='calender'),
# Example: calendar/11_00am/12_00pm
## Views (Note: Setting them as None allows you two have 2 URL paths pointing to a single view)
def calender(request, StartDate=None, EndDate=None):
  if StartDate and EndDate:
    # do things
    #   maybe render a different template or maybe just pass to render

    # EndDate = EndDate.replace('_', ':') # 12:00pm format

return render(request, 'calender.html')

2 Using GET parameters

## Urls
# Notes:
#   Single Path, Will pass parameters with GET
#   Generally you have to manually attach GETs to a URL (Either in Template Logic <a> , or Javascript) 

path('calender', views.calender, name='calender'),
# Example: calendar?StartDate=11_00am&EndDate=12_00pm
## Views
def calender(request):
  # Note: Using GET.get() will return None if it's not there
  #   which is probably better than GET[] which would crash if it's not there
  StartDate = request.GET.get('StartDate')
  EndDate = request.GET.get('EndDate')
  if StartDate and EndDate:
    # do things
    #   maybe render a different template or maybe just pass to render

    # EndDate = EndDate.replace('_', ':') # 12:00pm format

return render(request, 'calender.html')

edit

And this is just very general. Sorry I used Calendar as the examples instead of succ.html, was my bad. Naturally just copy some of that into succ and it’ll work the same. Hope you find this useful! :-)

  • Related