From 8f9e1b5877483b4d0c269d6989b511560e7cab89 Mon Sep 17 00:00:00 2001 From: reverend Date: Wed, 5 Aug 2020 10:15:51 +0200 Subject: [PATCH] Error message in the form when the voucher is invalid --- lostplaces/lostplaces_app/forms.py | 61 +++++++++++++++--------------- 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/lostplaces/lostplaces_app/forms.py b/lostplaces/lostplaces_app/forms.py index 6472aeb..69e9a2d 100644 --- a/lostplaces/lostplaces_app/forms.py +++ b/lostplaces/lostplaces_app/forms.py @@ -8,42 +8,43 @@ from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import Explorer, Place, PlaceImage, Voucher class ExplorerCreationForm(UserCreationForm): - class Meta: - model = Explorer - fields = ('username', 'email') - voucher = forms.CharField(max_length=10, help_text='The Voucher you got from an administrator') + class Meta: + model = Explorer + fields = ('username', 'email') + voucher = forms.CharField(max_length=10, help_text='The Voucher you got from an administrator') - def is_valid(self): - super().is_valid() - sumitted_voucher = self.cleaned_data.get('voucher') - try: - fetched_voucher = Voucher.objects.get(code=sumitted_voucher) - except Voucher.DoesNotExist: - return False + def is_valid(self): + super().is_valid() + sumitted_voucher = self.cleaned_data.get('voucher') + try: + fetched_voucher = Voucher.objects.get(code=sumitted_voucher) + except Voucher.DoesNotExist: + self.add_error('voucher', 'Invalid voucher') + return False - fetched_voucher.delete() - return True + fetched_voucher.delete() + return True class ExplorerChangeForm(UserChangeForm): - class Meta: - model = Explorer - fields = ('username', 'email') + class Meta: + model = Explorer + fields = ('username', 'email') class PlaceForm(forms.ModelForm): - class Meta: - model = Place - fields = '__all__' - exclude = ['submitted_by'] - + class Meta: + model = Place + fields = '__all__' + exclude = ['submitted_by'] + class PlaceImageCreateForm(forms.ModelForm): - class Meta: - model = PlaceImage - fields = ['filename'] - widgets = { - 'filename': forms.ClearableFileInput(attrs={'multiple': True}) - } + class Meta: + model = PlaceImage + fields = ['filename'] + widgets = { + 'filename': forms.ClearableFileInput(attrs={'multiple': True}) + } - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) - self.fields['filename'].required = False + self.fields['filename'].required = False