[英]How do I raise a ValidationError (or do something similar) in views.py of my Django?
我正在使用Django表單。 我在模型層驗證:
def clean_title(self):
title = self.cleaned_data['title']
if len(title) < 5:
raise forms.ValidationError("Headline must be more than 5 characters.")
return title
但是,我需要在views.py
驗證一些內容。 例如......是用戶最后一次發布超過一分鍾的內容嗎?
這種東西需要request.user,模型層無法獲取。 所以,我必須在views.py中驗證。 我如何在views.py中做一些事情來做到這一點?
raise forms.ValidationError("Headline must be more than 5 characters.")
我認為gruszczy的答案很好,但是如果你在涉及你認為只在視圖中可用的變量的泛型驗證之后,這里有另一種選擇:將vars作為參數傳遞給表單並以表格的形式處理它們clean()方法。
這里的區別/優勢在於您的視圖更加簡單,並且與表單內容相關的所有內容都可以在表單中進行。
例如:
# IN YOUR VIEW
# pass request.user as a keyword argument to the form
myform = MyForm(user=request.user)
# IN YOUR forms.py
# at the top:
from myapp.foo.bar import ok_to_post # some abstracted utility you write to rate-limit posting
# and in your particular Form definition
class MyForm(forms.Form)
... your fields here ...
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user') # cache the user object you pass in
super(MyForm, self).__init__(*args, **kwargs) # and carry on to init the form
def clean(self):
# test the rate limit by passing in the cached user object
if not ok_to_post(self.user): # use your throttling utility here
raise forms.ValidationError("You cannot post more than once every x minutes")
return self.cleaned_data # never forget this! ;o)
請注意,在clean()
方法中引發通用ValidationError
會將錯誤放入myform.non_field_errors
因此如果您手動顯示表單,則必須確保模板包含{{form.non_field_errors}}
您不在視圖中使用ValidationError
,因為這些例外與表單一樣。 相反,你應該將用戶重定向到其他網址,這將向他解釋,他不能很快再次發布。 這是處理這些東西的正確方法。 當輸入數據未驗證時,應在Form
實例內引發ValidationError
。 不是這種情況。
您可以在視圖中使用消息:
from django.contrib import messages
messages.error(request, "Error!")
文檔: https : //docs.djangoproject.com/es/1.9/ref/contrib/messages/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.