In Django, how do I put a form error into my views.py?
def clean_title(self):
title = self.cleaned_data['title']
if len(title) < 5:
raise form开发者_运维技巧s.ValidationError("Please write more in Title.")
return title
In my models.py, this is usually how I set an error form my title.
However, what if I want to do it in views.py? I want to set an error like that, except in the logic of my code.
Form errors are stored in a dictionary (ErrorDict from django.forms.util
) that maps field name to ErrorList class. Look at _clean_fields method - you would need to call your form clean()
method, then delete appropriate field from cleaned_data
attribute and do something like this:
your_form._errors[ "your_field" ] = ErrorList( [ "Your error message" ] )
精彩评论