首页 > 代码库 > 循序渐进Python3(十三) --0-- django之form表单

循序渐进Python3(十三) --0-- django之form表单

django为我们提供了form表单验证功能,下面来学习一下:
武sir博客:http://www.cnblogs.com/wupeiqi/articles/5246483.html 

创建了django项目之后,创建app。
技术分享

技术分享
 配置urls:
  1. from django.conf.urls import url
  2. from django.contrib import admin
  3. from myapp01 import views
  4. urlpatterns = [
  5. url(r‘^admin/‘, admin.site.urls),
  6. url(r‘^login/‘, views.login),
  7. ]
配置views(app01.views):
  1. from django.shortcuts import render
  2. from django import forms
  3. # Create your views here.
  4. class InputForm(forms.Form):
  5. # 下面使用的变量名必须和html中input标签的name值相同
  6. username = forms.CharField(required=True)
  7. password = forms.CharField(required=True)
  8. def login(request):
  9. if request.method == ‘POST‘:
  10. obj = InputForm(request.POST)
  11. ret = obj.is_valid()
  12. print(ret,obj.data)
  13. if ret:
  14. print(obj.clean())
  15. else:
  16. print(obj.errors)
  17. return render(request, ‘login.html‘)

配置tamplates(index.html):
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <div>
  9. <div>
  10. <input type="text" name="username" />
  11. </div>
  12. <div>
  13. <input type="password" name="password" />
  14. </div>
  15. <input type="button" value="提交" onclick="DoSubmit();"/>
  16. </div>
  17. <script src="/static/jquery-2.1.4.min.js"></script>
  18. <script>
  19. function DoSubmit() {
  20. var input_dic = {};
  21. $(‘input‘).each(function () {
  22. var v = $(this).val();
  23. var n = $(this).attr(‘name‘);
  24. input_dic[n] = v;
  25. });
  26. console.log(input_dic);
  27. $.ajax({
  28. url:‘/login/‘,
  29. type:‘POST‘,
  30. data:input_dic,
  31. success: function (rdata) {
  32. console.log(rdata);
  33. },
  34. error: function () {
  35. }
  36. })
  37. }
  38. </script>
  39. </body>
  40. </html>

 访问http://127.0.0.1:8000/login/ 
 提交之后就可以获取输入的内容。
技术分享
技术分享

 技术分享
技术分享
 
 


null


循序渐进Python3(十三) --0-- django之form表单