zoukankan      html  css  js  c++  java
  • django最简单表单入门

    两个html页面,存放于某个应用下的templates文件夹下。

    index.html

    点击“提交”按钮后,会调入第二个页面hello.html显示文本框的内容

    原理是通过form的action调用相应的方法执行操作

    index.html代码如下:

    <form action="/ok/"  method="POST">
            <input type="text" name="q">      
            <button type="submit">提交</button>
    </form>

    动作"/ok/" 其实是调用views.py中‘ok'方法

    views.py代码如下:

    from django.shortcuts import render_to_response
    
    def index(req):
        return render_to_response('index.html')
    
    def ok(req):
        x=req.POST['q']
        return render_to_response('hello.html',{'val':x})

    第一个index方法是调入首页

    第二个ok方法是处理表单的。通过req.POST['q']方法取得name值为'q'的文本框的值,赋值给变量x,

    再将此值传给模板变量val,在页面上显示。

    还要把ok方法添加到url映射中去

    urls.py的代码如下:

    urlpatterns = [
        url(r'^app1/','app1.views.index'),
        url(r'^ok/','app1.views.ok'),

    第二个页面的代码:

    <html>
    
      你提交的内容是:{{ val }}
    
    </html>

    如果出现错误的话,就在第一个页面代码中加下

    {% csrf_token %} 好像是防止攻击什么的。
     
  • 相关阅读:
    2018-10-25 模拟测试题解
    bzoj1218 [HNOI2003]激光炸弹题解
    poj1958 Strange Towers of Hanoi 题解
    NOIP2018游记
    6-序列公共用法:索引和切片
    5-编码格式
    4-格式化
    3-课后习题记录-就放这里了
    2-条件语句和循环语句
    1-基本数据类型的操作
  • 原文地址:https://www.cnblogs.com/jmlovepython/p/5022834.html
Copyright © 2011-2022 走看看