Can anyone help me to resolve MultiValueDictKeyError in django

I have added a drop-down in HTML for taking input, but I am getting an error MultiValueDictKeyError. Here I am sharing HTML code and Django code.

<form method = "POST" style = "text-align:center;">
   {% csrf_token %}
    {% comment %} <input type = "text" name = "consumer_id" placeholder = "Consumer Id" /> {% endcomment %}
   <fieldset style = "font-size:15px;">
   <select name = "Consumer_ID">
 <option value="0">Select </option>
  <option value="LT044T">LT044T</option>
  {% comment %} <option value="2P">2P</option> {% endcomment %}
 </select>
</fieldset>
 <input type = "text" name = "fromdate" placeholder = "FROM: DD-MM-YYYY" />
  <input type = "text" name = "todate" placeholder = "FROM: DD-MM-YYYY" />
<input type = "submit" value = "Search"/>
</form>

Here I am sending my view.py

if request.method == 'POST':
        start_date = request.POST['fromdate']
        print(start_date)
        end_date = request.POST['todate']
        print(end_date)
        consumer_id = request.POST['consumer_id']
        print(consumer_id)
    else:
        start_date = "01-05-2022"
        end_date = "04-05-2022"
        consumer_id = "hello"
    

Access form data using request.POST.get().

So your code must be :

if request.method == 'POST':
    start_date = request.POST.get('fromdate')
    print(start_date)
    end_date = request.POST.get('todate')
    print(end_date)
    consumer_id = request.POST.get('consumer_id')
    print(consumer_id)
else:
    start_date = "01-05-2022"
    end_date = "04-05-2022"
    consumer_id = "hello"
Back to Top