码迷,mamicode.com
首页 > 其他好文 > 详细

django基于模型的表单

时间:2019-11-04 13:50:25      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:short   用户名   lan   render   app   rms   inline   textinput   sha   

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基于模型的表单

标签:short   用户名   lan   render   app   rms   inline   textinput   sha   

原文地址:https://www.cnblogs.com/harryTree/p/11791404.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!