django基于模型的表单
Posted harrytree
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django基于模型的表单相关的知识,希望对你有一定的参考价值。
1.url路由-------------------------------
path("test/", app01_views.test)
2.views.py视图和基于模型的表单-----------------------------------
from django.shortcuts import render, HttpResponse
# Create your views here.
from django.db import connection
from app01.models import *
from django.db.models import Max,Min
from django import forms
from django.forms import widgets
from 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/bootstrap@3.3.7/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、运行结果---------------------------
以上是关于django基于模型的表单的主要内容,如果未能解决你的问题,请参考以下文章