Django之form校验&后台管理
django-form表单数据校验
#form 数据校验 class StudentForm(forms.Form): name = forms.CharField(min_length=2, max_length=10,required=True) #校验长度、必填项 phone = forms.CharField(min_length=11, max_length=11) money = forms.FloatField(required=False) #非必填 def clean_phone(self): #钩子 phone = self.cleaned_data['phone'] if models.Student.objects.filter(phone=phone): raise ValidationError('手机号已存在') return phone def student(request): stu_form = StudentForm(request.POST) #获取接口入参数据 if stu_form.is_valid(): #校验是否合法 print('clean_data', stu_form.cleaned_data) #返回的是字典类型 models.Student.objects.create(**stu_form.cleaned_data) #插入数据库 data = {'msg': '校验成功','success_msg': stu_form.cleaned_data} else: data = {'msg': '校验失败', 'error_msg': stu_form.errors.get_json_data()} return HttpResponse(json.dumps(data, ensure_ascii=False))
diango后台管理平台
1. 后台添加管理员用户
python manage.py createsuperuser (admin 、 admin123456)
如下图:
2. 访问django后台管理, http://127.0.0.1:8000/admin/login/
3. diango后台配置管理
a. 配置表信息(admin.py)
from django.contrib import admin # Register your models here. from . import models #配置表 admin.site.register(models.Nav) admin.site.register(models.Article)