ValidationError in Django

Hi, I am very new to Django. I am working on a small project in which I use modelform. For the date field, I want to perform a custom check, that is, whenever a user enters a date before today's date, it should display an error message next to the date field. I wrote the code according to the django documentation, but it gives ValidationErrors for the raise statement in modelform. like ValidationError at / add_task / [u "Enter a valid date. Either today or after that." ]

Please help me how to overcome this problem. Thanks in advance.

Codes of my models:

from django.db import models class MyTask(models.Model): summary=models.CharField(max_length=100) description=models.CharField(max_length=500) due_date=models.DateField(null=True) completed_status=models.BooleanField() def __unicode__(self): return self.summary 

My model codes:

 from django.forms import ModelForm, Textarea from django.forms.extras.widgets import SelectDateWidget from django.core.exceptions import ValidationError from assignment.models import MyTask import datetime class AddTaskForm(ModelForm): class Meta: model=MyTask fields=('summary','description','due_date') widgets = { 'description': Textarea(attrs={'cols': 50, 'rows': 10}), 'due_date':SelectDateWidget(), } def get_due_date(self): diff=self.cleaned_data['due_date']-datetime.date.today() if diff.days<0: raise ValidationError("Please enter valid date. Either today date or after that.") else: return self.cleaned_data['due_date'] def get_summary(self): return self.cleaned_data['summary'] def get_description(self): return self.cleaned_data['description'] 
+4
source share
1 answer

Your validation method should be called clean_due_date . And it should raise forms.ValidationError , not core.exceptions.ValidationError .

I have no idea what the get_summary and get_description methods are for, they are not called, and they don’t do anything useful.

+8
source

Source: https://habr.com/ru/post/1386993/


All Articles