I need some help understand Django form validators
I've read the Django documentation here: http://docs.djangoproject.com/en/dev/ref/forms/validation/
I've also browsed a number of search results on Google and Stack Overflow, but I haven't been able to answer my questions below.
As an example, say I have a model named "Widgets" with a CharField named "product_name". Now say that I want to restrict the allowable characters in "product_name" to [a-zA-Z0-9] plus apostrophes, dashes and underlines (i.e. ' - _) and show a form error to the user if they enter a restricted character.
From the above research, I gather that I need to create a validation function somewhere to check for these characters.
My specific questions:
1. What is best practice as to where a validation function like this should live in my Django project? 2. From where do I call this validation function? 3. 开发者_如何学GoHow do I show an error to the user if a "bad" character is entered? 4. Would someone be so kind as to post a sample validation function?Thank you, I appreciate any help you can provide.
Go with Chefsmart's answer if you can. Here is an example of a sample validation function in case it helps:
class MyCustomInvoiceForm(forms.Form):
serial_number = forms.IntegerField(min_value = 1, initial = 1)
# Other fields. I am interested in serial_number.
def clean_serial_number(self):
serial_number = self.cleaned_data.get('serial_number')
if not serial_number:
return
return _my_custom_validation(serial_number)
def _my_custom_validation(self, serial_number):
serial_number = int(serial_number)
if not ((serial_number - 1) % 10 == 0):
message = "Serial number should be 1 or one greater than a multiple of 10 (Example: 1, 11, 21 etc.)"
raise forms.ValidationError(message)
return serial_number
This is a snippet of code from a project I did. The customer required some interesting verification logic for serial number.
If you are using a Django form, you have the option of using a RegexField for your product_name field. See http://docs.djangoproject.com/en/1.2/ref/forms/fields/#regexfield
That would be the cleanest approach for your situation.
精彩评论