roselearn

导航

Django实现向数据库提交数据

  • 前台界面

  post请求需要加上 {% csrf_token %} 否则会报错,或者在Settings.py中的 'django.middleware.csrf.CsrfViewMiddleware' 注释掉

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>个人信息提交</title>
</head>
<body>

<form method="post">
    {% csrf_token %}
    <p>
        <span>姓名</span>
        <input type="text" id="nameid" name="name">
    </p>
    <p>
        <span>年龄</span>
        <input type="text" id="ageid" name="age">
    </p>
    <p>
        <span>邮箱</span>
        <input type="text" id="emailid" name="email">
    </p>
    <input type="submit" value="提交">
    <p>提交结果:{{msg}}</p>   
</form>
</body>
</html>

  前端界面效果

  • 视图

from .models import Student

def info_post(request):
    context = {
        "msg":""
    }
    if request.method == "GET":
        return render(request,"info_post.html")
    elif request.method == "POST":
        #获取前端输入的信息
        name = request.POST.get("name")
        age = request.POST.get("age")
        email = request.POST.get("email")
        #通过输入的name在数据库中查询是否存在
        infoobj = Student.objects.filter(name=name)
        if infoobj:
            context["msg"] = "姓名{}已存在".format(name)
            return render(request,"info_post.html",context=context)
        else:
            #若不存在,则插入数据
            info = Student()
            info.name = name
            info.age = age
            info.email = email
            info.save()
            context["msg"] = "姓名{}-年龄{}-邮件{}提交成功".format(name,age,email)
            return render(request,"info_post.html",context=context)
    else:
        return render(request, "info_post.html", context=context)
  • 具体效果

  输入王一查询已存在

   输入不存在的姓名提交到数据库成功

 

posted on 2023-02-01 13:19  dongzs  阅读(127)  评论(0编辑  收藏  举报