标签:content 视图 mat fail nbsp inpu http ror _for
# modelform的简单使用 # 1.models.py class UserAsk(models.Model): name = models.CharField(max_length=20, verbose_name="姓名") mobile = models.CharField(max_length=11, verbose_name="手机") course_name = models.CharField(max_length=50, verbose_name="课程") add_time = models.DateTimeField(auto_add_now=True, verbose_name="添加时间") # 2.modelform.py from django import form from operation.models import UserAsk import re class UserAskForm(form.ModelForm): class Meta: # 指定模型类 model = UserAsk # 指定模型类中字段 field = [‘name‘, ‘mobile‘, ‘course_name‘] # 自定义modelform验证,方法以clean开头 def clean_mobile(self): mobile = self.cleaned_data[‘mobile‘] REGEX_MOBILE = "^1[138]\d{9}$|^147\d{8}$|^176\d{8}$" p = re.compile(REGEX_MOBILE) if p.match(mobile): return mobile else: raise forms.ValidationError("手机号码非法", code="mobile_invalid") # 3.views.py # 添加留言的操作视图 from django.http import HeetResponse from .modelforms import UserAskForm class AddUserAskView(View): def post(self, request): userask_form = UserAskForm(request.POST) if userask_form.is_valid(): # modelform可以直接保存input框输入验证通过的值 user_ask = userask_form.save(commit=True) # 当前表单是页面部分提交,ajax异步请求,所以返回json字符串 return HttpResponse("{‘status‘:‘success}", content_type=‘application/json‘) else: return HttpResponse("{‘status‘:‘fail‘, ‘msg‘:{0}}".format(userask_form.errors)) # 4.urls.py from .views import AddUserAskView ... url(r‘^add_ask/$‘, AddUserAskView.as_view(), name="add_ask")
标签:content 视图 mat fail nbsp inpu http ror _for
原文地址:http://www.cnblogs.com/pymkl/p/7909045.html