I have a form that has a set of fields. For example it could be: name, surname and email. Form has two submit button on it: save and close. And there are two validation scenarios.
In first after 'save' button was clicked form 开发者_运维技巧checks whether field "name" has a value or not. If it has the Database will be updated.
In second scenario I click on 'close' button. And there should be another validation: name is not empty and contains certain value, surname is not empty and email contains some certain domain.
So how can i implement all these validation scenarios for one form. I see only bad solution like it will be some if-else statements in form clean() method.
I don't see why it would be so bad to have if/else in the save()
method. I'd probably do something like this:
def clean_save(self):
#validation for the save case
def clean_close(self):
#validation for the close case
def clean(self):
cleaned_data = self.cleaned_data
if cleaned_data.get('save_button'):
return self.clean_save()
elif cleaned_data.get('close_button'):
return self.clean_close()
else:
raise ValidationError('some error message')
I'm writing this from my head and haven't tested it but an approach like this should be good for keeping the validation out of the view.
I think the form validation should keep to the fields' types (e.g. make sure that a field which is not supposed to be empty is not). I'd put the validation you suggest in the view. It will be a sort of if-then-else, but it will be based on the button pressed.
精彩评论