开发者

In Django, how do I put a form error into my views.py?

开发者 https://www.devze.com 2023-01-28 04:57 出处:网络
def clean_title(self): title = self.cleaned_data[\'title\'] if len(title)< 5: raise form开发者_运维技巧s.ValidationError(\"Please write more in Title.\")
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" ] )
0

精彩评论

暂无评论...
验证码 换一张
取 消