I’ve got a relatively simple two field form that I can’t seem to properly validate. The meal_type
field is a radio button with three choices (Breakfast, Lunch, & Dinner). The date field is just that: date only, no time.
What the current code does when Save is clicked:
- If no radio button is checked, the error message is the default “Please select one of these options”. I’ve not yet figured out how to change that message.
- If a radio button is checked, e.g.,
Dinner
, the error message is " Select a valid choice. 1 is not one of the available choices.. I’ve not yet figured how how to change that message either.
Current code, such as it is:
models.py
:
...
MEAL_CHOICES = [
(3, 'Breakfast'),
(2, 'Lunch'),
(1, 'Dinner'),
]
def validate_meal_choice(value):
if value not in [1, 2, 3]:
raise ValidationError('Meal type not selected')
class Meal(models.Model):
meal_type = models.CharField(
choices=MEAL_CHOICES,
max_length=9,
default = None,
validators=[validate_meal_choice]
)
date = models.DateField()
foods = models.ManyToManyField(Food)
def __str__(self):
if self.meal_type == '1':
return 'Dinner'
elif self.meal_type == '2':
return 'Dinner'
else:
return 'Breakfast'
def save(self, *args, **kwargs) :
print('are we ok?')
return super().save(*args, **kwargs)
class Meta:
db_table = "meal"
ordering = ['-date', 'meal_type']
verbose_name = 'Meal type'
unique_together = [['meal_type', 'date']]
# constraints = [
# models.UniqueConstraint(
# fields=['meal_type', 'date'],
# condition=Q(date__date__gt=datetime.date(2005, 1, 1)),
# # condition=Q('meal_type_in["1", "2", "3"]'),
# name='unique_meal_date',
# # violation_error_message="Meal already created"
# )]
class MealForm(ModelForm):
class Meta:
model = Meal
fields = ['meal_type', 'date']
widgets = {
'meal_type' : forms.RadioSelect(),
'date' : DatePickerInput}
def clean_date(self):
print('so far, date check')
beginning = Meal.objects.all()[0].date
data = self.cleaned_data['date']
if data < beginning:
raise ValidationError("Date is earlier than earliest meal")
return data
def clean_meal(self):
print('so far, meal check')
ml = self.cleaned_data['meal_type']
if ml == "":
raise ValidationError("Date is earlier than earliest meal")
return ml
views.py
:
...
def mealNew(request):
if request.method == 'POST':
form = MealForm(request.POST)
if form.is_valid():
print('is this really good?')
else:
print('failed post')
else:
form = MealForm()
print('not posted!')
body = 'meal/new_meal_form.html'
context = {
'body' : body,
'title' : 'New Meal',
'form' : form
}
return render(request, 'base.html', context)