1.url路由-------------------------------path("test/", app01_views.test) 2.views.py视图和基于模型的表单----------------------------------- from django.shortcuts import render, HttpResponse # Create your views here. from django.db import connectionfrom app01.models import *from django.db.models import Max,Min from django import formsfrom django.forms import widgetsfrom django.db import models class NameModle( models.Model ): your_name = models.CharField(max_length=6) your_password = models.CharField( max_length=8 ) class NameForm(forms.ModelForm): class Meta: model = NameModle fields = [ "your_name", "your_password" ] # fields = "__all__" error_messages = { "your_name":{ "required":"用户名不能为空",}, "your_password": {"required": "密码不能为空", }, } widgets = { "your_name": widgets.TextInput( attrs={ "class":"form-control" }, ), "your_password": widgets.TextInput(attrs={"class": "form-control"}, ), } # class NameForm( forms.Form ):# your_name = forms.CharField(required=True , max_length=6, label="your name" ,# error_messages={# "required" : "your name must have",# "max_length": "用户名最大长度不超过6",# },# widget = widgets.PasswordInput( attrs={"class":"form-control", } ),# )# your_password = forms.CharField(max_length=8 , label="your password") def test(request): if request.method == "POST": print("come post") form = NameForm( request.POST ) if form.is_valid(): print("验证通过") print(form.cleaned_data) else: print("验证失败") print(form.errors) else: form = NameForm() return render(request, "home.html", {"form": form}) 3.templates/home.html模板-------------------------------------<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <body> <div class="container"> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <form action="/test/" method="POST" oninvalid class="form-inline"> {% csrf_token %} {% for field in form %} <div class="form-group"> {{ field.label }} {{ field }} {{ field.errors.0 }} <div > {% endfor %} <input type="submit" class="btn btn-default" value="Submit"> </form> </div> <div class="col-md-3"></div> </div> </div> </body></html> 4、运行结果---------------------------
原文地址:https://www.cnblogs.com/harryTree/p/11791404.html
时间: 2024-10-12 15:28:27