简体   繁体   中英

ValueError at / time data '' does not match format '%Y-%m-%d'

I'm working on a project in which when users mention a specific date range from and to, the corresponding data gets printed. The page takes input from users through input type date when the specific date is mentioned the value of date passes to user_input_date_to and user_input_date_to . But when I'm executing I'm getting the error ValueError at / time data '' does not match format '%Y-%m-%d'

My views file

def indexview(request):
    url=requests.get('https://data.covid19india.org/v4/min/timeseries.min.json')
    json_data=url.json()

    user_input_state=''
    user_input_date_from=''
    user_input_date_to=''
    user_data_type=''
    user_required_type=''
    if request.method == 'POST':
        user_input_state=request.POST.get('state')
        x=request.POST['date_from']
        user_input_date_to=request.POST['date_to']
        user_data_type=request.POST.get('data_period')
        user_required_type=request.POST.get('required_type')
        #To store dates list
    start_date =user_input_date_from
    end_date = user_input_date_to
    start_date_object = dt.datetime.strptime(start_date,"%Y-%m-%d").date()
    end_date_object = dt.datetime.strptime(end_date,"%Y-%m-%d").date()
    days = end_date_object - start_date_object
    dates=[]
    otp=[]
    for i in range(days.days+1):
        dates.append(str(start_date_object+dt.timedelta(days=i)))
    
    for i in dates:
        try:
            otp.append(json_data[user_input_state]['dates'][i][user_data_type][user_required_type])
        except KeyError:
            otp.append(0)
    
    dict_pass={
        'dates':dates,
        'otp':otp
        }
    return render(request,'index.html',dict_pass)

HTML date form

 <input type="date" name="date_from"><br>  
 <input type="date" name="date_to">  

The problem is, that you are trying to create datetime object of format '%Y-%m-%d' from the invalid user input (in your case it's empty string).

You should validate user input first, then do the business logic.

You could do it manually, or try to use existing libraries for the validation (eg pydantic , marshmallow ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM