django的Form
Posted xone
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django的Form相关的知识,希望对你有一定的参考价值。
django的Form组件
实例:
视图函数
from django import forms from app01 import models from django.forms import fields class FM(forms.Form): user = fields.CharField( error_messages={ ‘required‘:‘用户名不能为空‘ }) passwd = fields.CharField( max_length=12, min_length=6, error_messages={ ‘required‘:‘密码不能为空‘, ‘max_length‘:‘密码长度不能大于12‘, ‘min_length‘:‘密码长度不能小于6‘ }) email = fields.EmailField( error_messages={ ‘required‘:‘邮箱不能为空‘, ‘invalid‘:‘邮箱格式不正确‘ }) def fm(request): if request.method == ‘GET‘: obj = FM() return render(request,‘fm.html‘,{‘obj‘:obj}) elif request.method == ‘POST‘: obj = FM(request.POST) if obj.is_valid(): print(obj.cleaned_data) #返回的正确信息 models.User.objects.create(**obj.cleaned_data) return HttpResponse(‘OK‘) else: print(obj.errors.as_json()) #返回的所有错误信息 # print(obj.errors[‘user‘]) return render(request,‘fm.html‘,{‘obj‘:obj})
fm.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/fm/" method="POST"> {% csrf_token %} <p>{{ obj.user }} {{ obj.errors.user.0 }}</p> <p>{{ obj.passwd }} {{ obj.errors.passwd.0 }}</p> <p>{{ obj.email }} {{ obj.errors.email.0 }}</p> <p><input type="submit" value="提交"></p> </form> </body> </html>
以上是关于django的Form的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Django Summernote 中显示编程片段的代码块?
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE的解决办法(转)(代码片段
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE的解决办法(转)(代码片段
SpringBoot中表单提交报错“Content type ‘application/x-www-form-urlencoded;charset=UTF-8‘ not supported“(代码片段