Home > front end >  Set default url parameter or ignore the none input when nothing is specified - Django Project
Set default url parameter or ignore the none input when nothing is specified - Django Project

Time:02-25

I have a list of dictionaries:

mylist=
[{'Date': '10/2/2021', 'ID': 11773, 'Receiver': 'Mike'},
{'Date': '10/2/2021', 'ID': 15673, 'Receiver': 'Jane'},
{'Date': '10/3/2021', 'ID': 11773, 'Receiver': 'Mike'},
... 
{'Date': '12/25/2021', 'ID': 34653, 'Receiver': 'Jack'}]

I want to select the rows based on my input date range. I've successfully done this by appending the URL with ?start=val1&end=val2 and I was able to call the input date values from views.py to template.html :

Appending the URL with ?start=val1&end=val2 based on my input dates in my HTML

<div >
  <form method="get" action="/chart/">
    <div >
     <label for="start">Start Date:</label>
     <div >
        <input type="date"  name="start"  min="2020-01-03" required>
  </div>
  <label for="end">End Date:</label>
  <div >
      <input type="date"  name="end"  min="2020-01-03" required>
  </div>
  <button type="submit" > Generate Report</button>
</div>
</form>                   

Define start and end in my views.py:

start = request.GET.get('start', None)
end = request.GET.get('end', None)

Select the rows based on the input date range in my views.py:

dfmylist = pd.DataFrame(mylist)
dfmylist['Date'] = pd.to_datetime(dfmylist['Date']) # you missed this line
dfmylistnew = (dfmylist['Date'] > start) & (dfmylist['Date'] <= end)
new = dfmylist.loc[dfmylistnew]

And I was able to recall the {{new}} in my HTML. The only thing is, when I open the default URL, it shows the error: `Invalid comparison between dtype=datetime64[ns] and NoneType'. I know this is because no date values have been input, so the start & end will have no value.

What should I add in my views.py, so that the default URL without selected dates will assign a default value for start and end?

CodePudding user response:

Just add condition, which ensures that values are there:

dfmylist = pd.DataFrame(mylist)
dfmylist['Date'] = pd.to_datetime(dfmylist['Date'])
if start and end and dfmylist:
    dfmylistnew = (dfmylist['Date'] > start) & (dfmylist['Date'] <= end)
else:
    # do something when at least one of the variables is None
  • Related