Django 表单

自定义验证逻辑

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.forms import ModelForm,ValidationError
from app.models import Moment

class MomentForm(ModelForm):

    class Meta:
        model = Moment
        fields = '__all__' # 导入所有字段

    def clean(self):
        cleaned_data = super(MomentForm,self).clean()
        content = cleaned_data.get('content')
        if content is None:
            raise ValidationError('请输入内容!')
        elif content.find('ABCD') >=0:
            raise ValidationError('不能输入敏感字ABCD')
        return cleaned_data

检查变更字段

Django用has_changed()来判断用户是否修改过数据

def view_moment(request):
    data = {'content':'lalllalaaaaa',
            'usernae':'erha',
            'kind':'python技术'}
    f = MomentForm(request.POST,initial=data)
    if f.has_changed():
        print('如下字段做了修改:')
        for field in f.changed_data:
            print(field)

 

posted @ 2017-06-30 18:12  Erick-LONG  阅读(172)  评论(0编辑  收藏  举报