版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gang950502/article/details/82592054
第一个简单的form
html
<form action="/crm/cust_search/" method="get"> <input type="text" name="cust_id"> <input type="submit" value="Search"> </form>
urls
url(r'^cust_list/$',cust_list), url(r'^cust_search/$',cust_search),
models
def cust_list(request): return render(request,'cust_list.html') def cust_search(request): if "cust_id" in request.GET: message="You search for :%r" % request.GET['cust_id'] else: message="You submitted an empty form" return HttpResponse(message)
使用Django创建表单
自定义Form类如何关联到前台
Forms.py
from django import forms class add_user_form(forms.Form): #label可以指定标注 cust_id=forms.CharField(max_length=20,label=u"客户号") cust_name=forms.CharField(max_length=50,widget=forms.Textarea) #1.对公 2.对私 cust_type=forms.CharField(max_length=1,label=u"客户类型") card_type=forms.CharField(max_length=3) card_no=forms.CharField(max_length=20) cust_opdt=forms.CharField(max_length=20) cust_oprg=forms.CharField(max_length=20) cust_valied=forms.CharField(max_length=2) #可选: 附加校验条件 def clean_cust_type(self): cust_type=self.cleaned_data['cust_type'] if cust_type != '1' and cust_type != '2': raise forms.ValidationError("1-对公 2-对私") return cust_type
html
<form action="" method="post"> <table> {{ form.as_table }} </table> {% csrf_token %} <input type="submit" value="Submit"> </form>
这里as_table可以自动将Form中的所有元素放到页面前台上
views
def add_user(request): if request.method == "POST": form= add_user_form(request.POST) if form.is_valid(): return HttpResponse("添加成功") else: form = add_user_form( #可选:添加表单初始值 initial={'cust_id':'100000', 'cust_name':'张先生' } ) return render(request,'add_user.html',{'form':form})
自定义样式的添加
views
这里views 不用修改,仍然只需传入form对象即可
html
<style type="text/css"> ul.errorlist { margin: 0; padding: 0; } .errorlist li { background-color: red; color: white; display: block; font-size: 10px; margin: 0 0 3px; padding: 4px 5px; } </style> <form action="" method="post"> <div class="field"> {{ form.cust_id.errors }}<br> {{ form.cust_id.label }}: {{ form.cust_id }} </div> <input type="submit" value="Submit"> </form>
这里只示范了一个form元素的存放