文件目錄結構html
urls.pypython
from app1.views import account urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/',account.index), ]
settings.py數據庫
STATICFILES_DIRS =( os.path.join(BASE_DIR,'static') ) ##配置靜態路由
forms.pydjango
from django import forms from app1 import models class Form1(forms.Form): user =forms.CharField( # widget 自定義froms屬性 widget=forms.TextInput(attrs={'class':'c1'}), error_messages={'required':'用戶名不能夠爲空'}, ) # max_length最長多少位,min_length最少多少位 pwd =forms.CharField(max_length=4,min_length=2) # error_messages 錯誤信息 required 審覈是否爲空 invalid 格式是否正確 email =forms.EmailField(error_messages={'required':'郵件不能夠爲空', 'invalid':'郵箱格式錯誤', }) memo =forms.CharField( # Textarea文本下拉框 widget=forms.Textarea() ) user_type_choice=( (0,'人體學'), (1,'高級科技學'), ) # user_type_choice = models.BookType.objects.values_list('id', 'caption') ##從數據庫取數據 book_type =forms.CharField( widget=forms.widgets.Select(choices=user_type_choice, attrs={'class':"form-control"})) # Select 下拉框屬性 choices 選擇的東西 ,attrs獲取屬性
views.account.pyapp
from django.shortcuts import render # Create your views here. from app1.forms import Form1 def index(request): if request.method=='POST': f =Form1(request.POST)##判斷用戶輸入的是否合法 if f.is_valid():##若是用戶輸入的合法 print(f.cleaned_data) # cleaned_data中字段值是個model實例字典。 else:##不合法 print('&&&&&&&&&&&*********',f,'$$$$$$$$$$#########') return render(request,'account/form1.html',{'error':f.errors,'form':f}) else: f =Form1() ##空值, return render(request,'account/form1.html',{'error':f.errors,'form':f})
form1.htmlpost
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/index/" method="post"> <div class="inline-group"> {{ form.user }} {# form.user用戶,error.user.0 判斷有沒有error信息 #} {% if error.user.0 %} <span>{{ error.user.0 }}</span> {% endif %} </div> <div class="inline-group"> {{ form.pwd }} {% if error.pwd.0 %} <span>{{ error.pwd.0 }}</span> {% endif %} </div> <div class="inline-group"> {{ form.email }} {% if error.email.0 %} <span>{{ error.email.0 }}</span> {% endif %} </div> <div class="inline-group"> {{ form.memo }} {% if error.memo.0 %} <span>{{ error.memo.0 }}</span> {% endif %} </div> <div class="inline-group"> {{ form.book_type }} {% if error.book_type.0 %} <span>{{ error.book_type.0 }}</span> {% endif %} </div> <div> <input type="submit" value="提交"> </div> </form> </body> </html>
輸出效果ui