为什么表单提交至数据库会出错!!!!

为什么表单提交至数据库会出错!!!!

这两天一直在弄Django表单提交的内容。一直使用的是在工程总体的urls.py中引入每个应用的url配置文件这种路由配置方式,一直显示路由出错,至今还未解决。

现用另一种方式来提交可以保存至数据库:这种路由配置方式为在Django工程的urls.py中针对每个应用分别配置不同的url路径就是只用项目的路由文件,不再另外创建应用路由文件。

项目的urls.py

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

from app1 import views

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

    path('index/', views.index),
    path('postTest1/', views.postTest1),
    path('postTest2/', views.postTest2),

]

模式


def index(request):
    body = Article.objects.all()
    return render_to_response("index.html",{"body":body})

def postTest1(request):
    return render(request, "postTest1.html")

def postTest2(request):
    if request.method == "POST":
        article = Article()
        article.title = request.POST.get("title")
        article.content = request.POST.get('content')
        article.tiemstamp = datetime.now()
        article.save()
        return HttpResponseRedirect('/index/')  # 重定向到index页面

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
</head>
<body>

<table>
    {% for item in body %}
        <tr>
            <td>{{ item.title }}</td>
            <td>{{ item.content }}</td>
            <td>{{ item.tiemstamp }}</td>
        </tr>
    {% endfor %}
</table>
</body>
</html>

postTest1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单提交测试</title>
</head>
<body>
<form action="/postTest2/" method="post">
    {% csrf_token %}
    标题:<input type="text" name="title"><br>
    内容:<textarea name="content" rows=3 cols="60"></textarea>
    <input type="submit" value="提交">
</form>
</body>
</html>

在这里插入图片描述

在这里插入图片描述

问题有待解决。。。。。。。。。

来更新了。使用项目路由和应用路由的表单提交方法如下:
主路由为:
在这里插入图片描述

应用路由为:
在这里插入图片描述
视图为:

def index(request):
    body = Article.objects.all()
    return render_to_response("index.html",{"body":body})

def postTest1(request):
    return render(request, "postTest1.html")

def postTest2(request):
    if request.method == "POST":
        article = Article()
        article.title = request.POST.get("title")
        article.content = request.POST.get('content')
        article.tiemstamp = datetime.now()
        article.save()
        return HttpResponseRedirect('/app1/index/')  # 重定向到index页面

postTest1 表单提交页面为:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值