django-form and fields validation
參考資料
清除數據與表單驗證
清除數據時會進行表單驗證。 在表格處理時有三種clean方法可調用,通常是在對表單調用is_valid()時執行。
clean響應:一般有兩種結果,如果處理的數據有問題,則拋出ValidationError錯誤信息;若是正常,則會返回一個類型為python對象的規范化data。
- 在field子類的clean方法,此方法返回干凈的數據,然后插入到表單的cleaned_data字典中。
- clean_() 方法在表單子類上調用。其中fieldname由表單字段名替代,此方法不返回任何參數。若查找self.cleaned_data字段中的值,記住這是一個python對象類型。
- 表單驗證流程:
- 對于form中的字段,按照順序運行Field.clean方法
- 運行clean_()
- 最后,無論之前兩步是否拋出了錯誤,都將執行Form.clean()方法。
在實踐中運用驗證
using validators
我們可以自定義form field,驗證輸入字符串是否符合預設值規范,比如說是電子郵件地址類型。
from django import forms from django.core.validators import validate_emailclass MultiEmailField(forms.Field):def to_python(self, value):"""Normalize data to a list of strings."""# Return an empty list if no input was given.if not value:return []return value.split(',')def validate(self, value):"""Check if value consists only of valid emails."""# Use the parent's handling of required fields, etc.super(MultiEmailField, self).validate(value)for email in value:validate_email(email)然后我們可以創建一個簡單的函數來使用自定義field
class ContactForm(forms.Form):subject = forms.CharField(max_length=100)message = forms.CharField()sender = forms.EmailField()recipients = MultiEmailField()cc_myself = forms.BooleanField(required=False)當在form中調用is_valid()方法時,自動使用了我們自定義的MultiEmailField()方法,它將作為clean過程中的一部分執行。
cleaning and validating fields that depend on each other
當我們同時驗證多個字段時,表單的form.clean()方法是個很好的選擇。
It's important to keep the field and form difference clear when working out where to validate things. Fields are single data points, forms are a collection of fields.
By the time the form's clean() method is called, all the individual field clean methods will have been run (the previous two sections), so self.cleaned_data will be populated with any data that has survived so far. So you also need to remember to allow for the fact that the fields you are wanting to validate might not have survived the initial individual field checks.
有兩種方法可以拋出該過程中出現的error.
第一種
在此過程中拋出的錯誤,我們可以用clean()方法中提供的ValidationError,令其在窗口頂部顯示錯誤。如:
from django import formsclass ContactForm(forms.Form):# Everything as before....def clean(self):cleaned_data = super(ContactForm, self).clean()cc_myself = cleaned_data.get("cc_myself")subject = cleaned_data.get("subject")if cc_myself and subject:# Only do something if both fields are valid so far.if "help" not in subject:raise forms.ValidationError("Did not send for 'help' in the subject despite ""CC'ing yourself.")在示例代碼中對 super(ContactForm, self).clean() 的調用,確保可以實現父類中的所有驗證邏輯。
第二種
可以將error信息分配給一個指定field。
Form.add_error(field, error)
這種方法允許從 Form.clean() 方法內的特定字段添加錯誤,或者從外部添加錯誤;例如在視圖中。
但在開發環境中,我們要小心這種方式可能產生的輸出格式混亂,修改了上面代碼如下:
請注意,Form.add_error() 會自動從 cleaned_data 中刪除相關字段
Form.errors
訪問 errors 屬性以獲取錯誤消息的字典。注意這里的錯誤消息是dict形式傳出,但某個字段可以有多個error,故錯誤信息存儲在列表list中。
Form.errors.as_json(escape_html=False)
返回序列化為JSON的錯誤信息。
>>> f.errors.as_json() {"sender": [{"message": "Enter a valid email address.", "code": "invalid"}], "subject": [{"message": "This field is required.", "code": "required"}]}By default, as_json() does not escape its output. If you are using it for something like AJAX requests to a form view where the client interprets the response and inserts errors into the page, you'll want to be sure to escape the results on the client-side to avoid the possibility of a cross-site scripting attack. It's trivial to do so using a JavaScript library like jQuery - simply use $(el).text(errorText) rather than .html().
默認情況下,as_json()不會轉義輸出。如果你處理從表單來的AJAX請求,客戶端解釋這個響應并在頁面中插入錯誤信息。你需要確保在不遭受XSS攻擊的情況下轉義結果。如果使用JavaScript庫(如jQuery)這樣實現很簡單 - 只需使用 $(el).text(errorText),而不是 .html()。
Accessing the fields from the form
Form.fields
如何從字段訪問表單呢?
You can access the fields of Form instance from its fields attribute
>>> for row in f.fields.values(): print(row) ... <django.forms.fields.CharField object at 0x7ffaac632510> <django.forms.fields.URLField object at 0x7ffaac632f90> <django.forms.fields.CharField object at 0x7ffaac3aa050> >>> f.fields['name'] <django.forms.fields.CharField object at 0x7ffaac6324d0>我們也可修改 Form 實例的字段參數,以更改其在表單中顯示的方式
>>> f.as_table().split('\n')[0] '<tr><th>Name:</th><td><input name="name" type="text" value="instance" required /></td></tr>' >>> f.fields['name'].label = "Username" >>> f.as_table().split('\n')[0] '<tr><th>Username:</th><td><input name="name" type="text" value="instance" required /></td></tr>'Accessing "clean" data(The resources:https://docs.djangoproject.com/en/2.0/ref/forms/api/#accessing-clean-data)
Form 類中的每個字段不僅負責驗證數據,還負責“清理"它 "- 將其標準化為一致的格式。這是一個很好的功能,因為它允許以各種方式輸入特定字段的數據,轉換為一致類型的輸出。
For example, ~django.forms.DateField normalizes input into a Python datetime.date object. Regardless of whether you pass it a string in the format '1994-07-15', a datetime.date object, or a number of other formats, DateField will always normalize it to a datetime.date object as long as it's valid.
一旦您創建了一個具有一組數據并驗證它的 Form 實例,您可以通過其 cleaned_data 屬性訪問干凈的數據:
>>> data = {'subject': 'hello', ... 'message': 'Hi there', ... 'sender': 'foo@example.com', ... 'cc_myself': True} >>> f = ContactForm(data) >>> f.is_valid() True >>> f.cleaned_data {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}在這里,任何文本輸入的字段,如EmailField,CharField都會將輸入數據clean為標準字符串類型。
轉載于:https://www.cnblogs.com/dion-90/p/8443506.html
總結
以上是生活随笔為你收集整理的django-form and fields validation的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 主流影视网站8合一H5视频源码自动更新数
- 下一篇: mysql strtok_c函数: st