【问题标题】:Django HTML form input to db.sqlite3Django HTML 表单输入到 db.sqlite3
【发布时间】:2020-01-31 13:46:30
【问题描述】:

我正在制作一个简单的 Web 服务器来获取 html 输入数据并将其插入到数据库表中。

我尝试使用 POST 请求遇到更多 CSRF 麻烦,转向 GET 请求以通过 CSRF(在我的情况下不是必需的),仍然无法将 html 数据获取到数据库中。

myapp/models.py

from django.db import models


class Post(models.Model):
    title = models.CharField(max_length=300, unique=True)
    content = models.TextField()

myapp/templates/createpost.html

<head>
<title>Create a Post </title>
</head>

<body>
<h1>Create a Post </h1>
<form action="" method="GET">
    {%csrf_token%}
    Title: <input type="text" name="title"/><br/>
    Content: <br/>
    <textarea cols="35" rows="8" name="content">
        </textarea><br/>
    <input type="submit" value="Post"/>
</form>
</body>

</html>

myapp/views.py

from django.shortcuts import render
from .models import Post


def createpost(request):
    if request.method == 'GET':
        if request.GET.get('title', None) and request.GET.get('content', None):
            post = Post()
            post.title = request.GET.get('title', None)
            post.content = request.GET.get('content', None)
            post.save()
        return render(request, 'createpost.html')
    else:
        return render(request, 'createpost.html')

urls.py

from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='createpost.html'), name='createpost'),
]

我正在使用 Django 2.2.6 和 PyCharm 社区 2019.2.3 我已经搜索了将近 2 天,检查了 django doc 和 stackoverflow 答案,没有任何帮助,我不得不询问以确保它不是与版本相关的问题,如果我错过了一个简单的点,请原谅我只是一个初学者。

【问题讨论】:

  • 你试过打印这个吗? request.GET.get('title', None) 是空的还是没有的?你得到了什么?
  • 我不知道该怎么做,我试过 python manage.py runserver 然后在另一个终端上调用 view.py 我不能,我试图将打印命令添加到视图和我根本没有输出
  • 好的,我的意思是,做print(request.GET.get('title', None)) 并再次提交表单并检查
  • 我做到了,根本没有打印,我得到的只是我的 GET 请求 [02/Oct/2019 03:00:01] "GET /?csrfmiddlewaretoken=Q0FAgroc1JbIOfKImoTIcMiX4qv1AGVYIy9quUdPSu16ttR1++++++++++++++++ /1.1" 200 440 试图从中提取标题和内容。
  • 显示您的网址。几乎可以肯定你没有发送到 createpost 视图。但无论如何你应该在这里使用 POST。

标签: django django-models django-templates django-views


【解决方案1】:

我尝试使用 POST 请求遇到更多 CSRF 麻烦,转向 GET 请求以通过 CSRF(在我的情况下不是必需的),仍然无法成功。

好的。

立即停止一切

现在

  1. 做 Django 官方教程,学习使用 Django 表单和模型表单
  2. 阅读有关正确使用 GET 请求的 HTTP 规范(提示:这里的重要词是“幂等”)
  3. 相应地修复您的代码
  4. 如果到那时您仍然对 csrf 令牌有疑问,请返回并发布有关它的问题(使用适当的 MCVE 等)。

另外请注意,您的问题应该被表述为不清楚或过时,因为您没有解释您的问题是什么(提示:“不起作用”并不能解释任何事情)。不过不管怎样……

你想要的(nb:模型不变)是:

myapp/forms.py

from django import forms
from . models import Post

class PostForm(forms.ModelForm):
    class Meta(object):
        model = Post
        fields = ("title", "content")

views.py

from django.shortcuts import redirect, render
from . models import Post
from . forms import PostForm

def createpost(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
            # read the doc for `redirect` and change the destination to
            # something that makes sense for your app.
            # as to why we redirect, cf  https://en.wikipedia.org/wiki/Post/Redirect/Get
            return redirect("/")

    else:
        # GET request, present an empty form
        form = PostForm() 
    return render(request, 'createpost.html', {"form": form})

urls.py

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

# NB: actually you should define myapp's urls in 
# myapp/urls.py and `include` them here
from myapp.views import createpost

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

myapp/templates/createpost.html

<head>
  <title>Create a Post </title>
</head>

<body>
  <h1>Create a Post </h1>
  <form action="" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Post"/>
   </form>
</body>

</html>

我不能保证这将开箱即用(我必须发布一个具有适当设置等的完整项目以确保 - 并且实际上至少测试一次以防错别字等)但这是正确的方法做事。

我已经搜索了将近 2 天

这是浪费了 2 天,你最好用做官方 Django 教程。我还建议您学习调试程序 - 只需在您的视图中添加几个 ̀print("XXX")` 调用并检查您的开发服务器的输出就会清楚为什么在您的数据库中没有创建任何内容(提示:使用您的原始 urls.py,你永远不会调用你的视图函数)。

【讨论】:

  • 感谢您的建议,我已经阅读了很多 .djangoproject 文档,但不是作为一个系列,只是与一些主题相关,我认为我的背景显然不是。我尝试使用 print 进行调试,但不知道如何调用 django 视图函数。
  • @George 这就是为什么您应该首先完成(整个!)教程的原因——它会引导您创建一个简单的项目,这样您就可以在深入了解更深入的细节之前了解整个情况。唯一需要注意的是教程坚持使用基于类的通用视图(这在大多数情况下只不过是一种只会让初学者感到困惑的无用并发症),以及它不呈现 django 表单和模型表单的事实(实际上是一个 非常 Django的重要部分)。
  • 是的,我现在完全同意,您的回答比 2 天的随机阅读和搜索更有帮助。我现在将按照教程进行操作。非常感谢您花时间帮助像我这样的初学者。
  • @George 不客气。我建议您也花时间学习基本的调试技术(如何跟踪代码执行、检查当前程序状态等 - 使用步进调试器的 IOW),这将为您节省大量时间'没有按预期工作-实际上,这是最常见的情况;-)
猜你喜欢
  • 2020-12-16
  • 2018-01-19
  • 1970-01-01
  • 2011-01-26
  • 1970-01-01
  • 2016-09-14
  • 2011-12-10
  • 2014-08-28
  • 2018-10-28
相关资源
最近更新 更多