为什么表单提交至数据库会出错!!!!
这两天一直在弄Django表单提交的内容。一直使用的是在工程总体的urls.py中引入每个应用的url配置文件这种路由配置方式,一直显示路由出错,至今还未解决。
现用另一种方式来提交可以保存至数据库:这种路由配置方式为在Django工程的urls.py中针对每个应用分别配置不同的url路径就是只用项目的路由文件,不再另外创建应用路由文件。
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 表单提交页面为: