zoukankan      html  css  js  c++  java
  • django前端到后端一次完整请求实例

    一、创建项目:
    # django-admin startproject mysite
    # cd mysite
    # python manage.py startapp blog

    目录结构:

      

    
    
    一、html文件:templates/userInfo.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title></title>
    </head>
    <body>
    <h1>数据提交:</h1>
    <form action="/userInfo" method="post">
    <p>姓名<input type="text" name="username"></p>
    <p>性别<input type="text" name="sex"></p>
    <p>邮箱<input type="text" name="email"></p>
    <p><input type="submit" name="submit"></p>
    </form>

    <hr>
    <h1>数据展示:</h1>
    <table border="1">
    <tr>
    <td>姓名</td>
    <td>性别</td>
    <td>邮箱</td>
    </tr>
    {% for i in user_list %}
    <tr>
    <td> {{ i.username }} </td>
    <td>{{ i.sex }} </td>
    <td>{{ i.email }} </td>
    </tr>
    {% endfor %}

    </table>
    </body>
    </html>

    二、修改配置文件:settings.py
    INSTALLED_APPS = [
    'blog', # 增加一个app
    ]
    MIDDLEWARE = [
    #'django.middleware.csrf.CsrfViewMiddleware', # 涉及到表单提交,这里把csrf相关注释了
    ]
    TEMPLATES 部分加入:
    'DIRS': [os.path.join(BASE_DIR,"templates")],   # 存放HTML文件的地方

    二、修改urls.py 文件:
    from blog import views

    urlpatterns = [
    url("userInfo",views.userInfo),
    ]
    三、编写对应视图函数:views.py

    from django.shortcuts import render,HttpResponse
    from  blog import models
    def userInfo(request):
    #return HttpResponse("<h1>xxx</h1>")
    if request.method == "POST":
    u = request.POST.get("username",None)
    s = request.POST.get("sex",None)
    e = request.POST.get("email",None)
    models.UserInfo.objects.create(
    username=u,
    sex = s ,
    email = e,
    )
    user_list=models.UserInfo.objects.all()
    return render(request,"userInfo.html",{"user_list":user_list})

    四:编写models.py :
    from django.db import models
    class UserInfo(models.Model):
    username = models.CharField(max_length=64)
    sex = models.CharField(max_length=64)
    email = models.CharField(max_length=64)
    #执行下面语句初始化数据库:
    #python manage.py makemigrations
    #python manage.py migrate

    五、打开html访问:

      















  • 相关阅读:
    ArcPad 10 的安装部署
    各种机械键盘轴的差别,究竟什么轴好
    default argument given of parameter 的问题
    Quartz中时间表达式的设置-----corn表达式
    图像切割之(一)概述
    SMTP协议分析
    Android学习小Demo(19)利用Loader来实时接收短信
    qml动画控制器AnimationController
    httpclient 文件上传
    Java习题10.24
  • 原文地址:https://www.cnblogs.com/fanxuanhui-linux/p/7966037.html
Copyright © 2011-2022 走看看