表单通过POST方式往数据库中写入数据

工程名称为demo7

一、直接POST提交:

models.py:

from django.db import models

# Create your models here.
class Article(models.Model):
    title = models.CharField(max_length=32, default='Title')
    content = models.TextField(null = True)

views.py:

from django.shortcuts import render
from django.views.decorators import csrf
from django.http import HttpResponse
from . import models

# Create your views here.

def add_article(request):
    ctx ={}
    if request.POST:
        ctx['title'] = request.POST['title']
        ctx['content'] = request.POST['content']
        test1  = models.Article(title=ctx['title'], content=ctx['content'])
        test1.save()
        all = models.Article.objects.all()
    return render(request, 'post.html', {'all': all})

post.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form action="/blog/add/" method="POST">
        {% csrf_token %}
        <input type="text" name="title"/><br/>
        <textarea name="content"></textarea><br/>
        <button>添加</button>
    </form>

    {% for a in all %}
        <p>{{a.title}}</p>
    {% endfor %}
</body>
</html>

blog/urls.py:

from django.urls import path, include
from . import views

urlpatterns = [
   path('add/', views.add_article)
]

 demo7/urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls'))
]

项目结构如下:

通过http://ip:port/blog/add/即可访问。

二、异步提交:

views.py:

from django.shortcuts import render
from django.views.decorators import csrf
from django.http import HttpResponse
from . import models
from django.views.decorators.csrf import csrf_exempt
import json

# Create your views here.

@csrf_exempt
def add_article(request):
    ctx ={}
    if request.POST:
        ctx['title'] = request.POST['title']
        ctx['content'] = request.POST['content']
        test1  = models.Article(title=ctx['title'], content=ctx['content'])
        test1.save()
        
        data = {'ret': True, 'msg': '数据提交成功!'}
        return HttpResponse(json.dumps(data), content_type="application/json")

@csrf_exempt
def add_page(request):
    return render(request, 'post.html')

post.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
    <form action="/blog/add/" method="POST">
        <input type="text" id="title"/><br />
        <textarea id="content"></textarea><br />
        <input id="submit-button" type="button" value="提交" />
    </form>

    <script>
        $("#submit-button").click(function () {
            $.ajax({
                cache: false,
                type: "POST",
                url: "/blog/add/",
                //traditional: true, //加上此项可以传数组
                dataType: 'json',
                data: { title: $("#title").val(), content: $("#content").val()},
                success: function (data) {
                    if(data.ret){
                        alert(data.msg)
                    }
                }
            });
        })
    </script>
</body>

</html>

blog/urls.py:

from django.urls import path, include
from . import views

urlpatterns = [
   path('add/', views.add_article),
   path('add_page/', views.add_page),
]

通过http://ip:port/blog/add_page/即可访问。

以下是一个示例代码,实现了动态增加表单,并通过PHP接收和处理所有表单数据,最终将数据写入数据库: HTML代码: ``` <!DOCTYPE html> <html> <head> <title>动态增加表单</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <body> <form id="myForm" action="process_form.php" method="post"> <fieldset> <legend>表单信息</legend> <div id="formContainer"> <div> <label>姓名:</label> <input type="text" name="name[]" required> </div> <div> <label>年龄:</label> <input type="number" name="age[]" required> </div> </div> <button type="button" id="addForm">增加表单</button> <button type="submit">提交</button> </fieldset> </form> <script> $(document).ready(function() { $("#addForm").click(function() { var newForm = '<div>' + '<label>姓名:</label>' + '<input type="text" name="name[]" required>' + '</div>' + '<div>' + '<label>年龄:</label>' + '<input type="number" name="age[]" required>' + '</div>'; $("#formContainer").append(newForm); }); }); </script> </body> </html> ``` JavaScript代码使用jQuery,当点击“增加表单”按钮时,会在`formContainer`动态添加一个新的表单。 PHP代码: ``` <?php // 连接数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // 获取表单数据 $nameArray = $_POST['name']; $ageArray = $_POST['age']; // 将数据写入数据库 for ($i = 0; $i < count($nameArray); $i++) { $name = $nameArray[$i]; $age = $ageArray[$i]; $sql = "INSERT INTO myTable (name, age) VALUES ('$name', $age)"; if ($conn->query($sql) !== TRUE) { echo "Error: " . $sql . "<br>" . $conn->error; } } // 关闭数据库连接 $conn->close(); ?> ``` PHP代码首先连接数据库,然后通过`$_POST`全局变量获取表单数据,使用`count()`函数获取表单数据的数量,遍历每个表单数据,将其写入数据库。最后关闭数据库连接。注意,这里直接将表单数据拼接到SQL语句,存在SQL注入的风险,应该使用参数化查询来避免这个问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值