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 %} 好像是防止攻击什么的。
     
  • 相关阅读:
    TCP和UDP协议?
    了解浏览器缓存机制吗?
    关于预检请求?
    cookie可设置哪些属性?httponly?
    http和https?
    vue自定义组件?
    实现页面回退刷新?
    vue3.0的更新和defineProperty优化?
    vue的seo问题?
    vuex组成和原理?
  • 原文地址:https://www.cnblogs.com/jmlovepython/p/5022834.html
Copyright © 2011-2022 走看看