Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate end_time is bigger than start_time django form

Tags:

python

django

I have start_time and end_time data fields in models and I want to assign an error when start_time is later than end_time.

forms.py

class RentForm(forms.ModelForm):
    class Meta:
        model = Rent
        fields = ['start_time', 'end_time']
    def clean(self):
        cleaned_data = super().clean()
        start_date = cleaned_data.get("start_time")
        end_date = cleaned_data.get("end_time")
        if start_time > end_time:
            raise forms.ValidationError("Error")

views.py

def rent_car(request):
    if request.method == 'POST':
        form = RentForm(request.POST or None)
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        form = RentForm(request.POST)
    return render(request, 'rent.html', {'form': form)

Unfortunately, I get an error

unsupported operand type(s) for -: 'NoneType' and 'NoneType'

Please help me solve this problem.

like image 434
Michson07 Avatar asked Dec 28 '25 15:12

Michson07


1 Answers

You use the form the wrong way. You should not use RentForm(request.POST) in case you create a form to render (for the time), since then you already store the values in the form. Furthermore using request.POST is not a good idea either, since a POST request can sometimes be perfectly valid, if there are not POST parameters. You thus should rewrite the view to:

def rent_car(request):
    if request.method == 'POST':
        form = RentForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        form = RentForm()
    return render(request, 'rent.html', {'form': form)

You might want to make the start_time and end_time required as well in your RentForm, and you have to return the cleaned_data in case the form is not invalid:

class RentForm(forms.ModelForm):
    start_time = forms.DateTimeField(required=True)
    end_time = forms.DateTimeField(required=True)

    class Meta:
        model = Rent
        fields = ['start_time', 'end_time']

    def clean(self):
        cleaned_data = super().clean()
        start_date = cleaned_data.get('start_time')
        end_date = cleaned_data.get('end_time')
        if start_time > end_time:
            raise forms.ValidationError("Error")
        return cleaned_data
like image 69
Willem Van Onsem Avatar answered Dec 30 '25 05:12

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!