getting wrong format of date in Django

Viewed 245

I am trying to create a form to receive date input from the user and then pass that input to my another python script my Django form code is as below

from Django import forms


class NameForm(forms.Form):
    lev=forms.IntegerField(label='lev')
    status = forms.CharField(label='status', max_length=100)
    start_date = forms.DateField(widget=forms.DateInput(format = '%Y/%m/%d',attrs={'type': 'date'}))

i am receiving the date and all other values in my views.py file and then passing them to my python script my views.py code is

def generate(request):
    form=NameForm(request.POST)
    if form.is_valid():
        a=str(form.cleaned_data.get('lev'))
        b= form.cleaned_data.get('status')
        c=str(form.cleaned_data.get('start_date'))
       


    output=run([sys.executable,'C:\\Users\\siddhant\\Desktop\\internship\\indicator\\work\\water.py',a,b,c],stdout=PIPE,text=True)
    

    events_list=level.objects.all()
    return render(request,'result.html',{'res':events_list})

and I am doing a strptime conversion of passed date in my work.py code as follow

current_level=int(sys.argv[1])
x=sys.argv[2]
start_date=sys.argv[3]
print(start_date)
start=datetime.strptime(start_date, "%y/%d/%m")

but i am getting error that ValueError: time data '2022-01-01' does not match format '%y/%d/%m' please can someone suggest how to do tackle with this problem

1 Answers

You need to format the date object properly when calling the function:

def generate(request):
    form = NameForm(request.POST)
    if form.is_valid():
        a = str(form.cleaned_data['lev'])
        b = form.cleaned_data.get('status')
        c = form.cleaned_data.get('start_date').strftime('%y/%d/%M')
        output=run([sys.executable,'C:\\Users\\siddhant\\Desktop\\internship\\indicator\\work\\water.py',a,b,c],stdout=PIPE,text=True)

In the water.py program, you should parse it with %M, not %m, otherwise you are parsing the minute, not the month:

current_level = int(sys.argv[1])
x = sys.argv[2]
start_date = sys.argv[3]
print(start_date)
start = datetime.strptime(start_date, "%y/%d/%M")
Related