【问题标题】:What's wrong with my code that user input won't go in django database?我的代码有什么问题,用户输入不会进入 django 数据库?
【发布时间】:2018-01-16 18:36:59
【问题描述】:

我想要的只是在用户点击Submit 时让用户输入进入数据库,但我在浏览器中收到一条错误消息:

RuntimeError at /content
You called this URL via POST, but the URL doesn't end in a slash and 
you have APPEND_SLASH set. 
Django can't redirect to the slash URL while maintaining POST data. 
Change your form to point to 127.0.0.1:8000/content/ (note the trailing 
slash), or set APPEND_SLASH=False in your Django settings.

我知道我非常接近实现这一目标,我只是想知道我错过了什么或我搞砸了。

这里是views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import Email
from django.core.exceptions import *

def index(request):
    return render(request, 'personal/home.html')

def contact(request):
    return render(request, 'personal/basic.html',{'content':['If you would like more information, leave your email.']})

def search(request):
    if request.method == 'POST':
        search_id = request.POST.get(name = search_id)
        try:
            user = Email.objects.get(name=search_id)
            # do something with user
            html = ("<H1>%s</H1>", user)
            return HttpResponse(html)
        except Email.DoesNotExist:
            return HttpResponse("no such user")
        else:
            return render(request, 'basic.html')

这里是urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^content/', views.contact, name='content'),
]

这里是basic.html

{% extends "personal/header.html" %}

{% block content %}
<style type="text/css">
    h1 {
        color: #2e6da4;
        font-family: Chalkboard;
    }

    .text {
        text-align: center;
    }
</style>

    {% for c in content %}
        <h1>{{c}}</h1>
    {% endfor %}

    <div class="form-group">
        <form method="POST" action="/content">
            {% csrf_token %}
            <input type="text" name="textfield">

            <button type="submit">Submit</button>
        </form>
        </div>
{% endblock %}

【问题讨论】:

  • 如果以下任何答案帮助您解决了问题,请将其标记为已接受。这是 StackOverflow 中的一个好习惯 :)
  • 如果以下任何答案帮助您解决了问题,请将其标记为已接受。这是 StackOverflow 中的一个好习惯 :)
  • @nik_m 有机会我会尝试一下,如果可行的话我会接受 :)。谢谢你提醒我!

标签: python html django sqlite jinja2


【解决方案1】:

这是因为您在 POST 处理 URL /content 上的数据,而不是 /content/。要么改成&lt;form method="POST" action="/content/"&gt;,要么改成&lt;form method="POST" action="{% url 'content' %}"&gt;,使用{% url %}模板标签。

【讨论】:

    【解决方案2】:

    Django 有一个特性,可以自动将 /content 等 URL 重定向到 /content/。但是,当您使用 POST HTTP 方法时,此功能不起作用。 Django 试图告诉你它试图做这个重定向,但它不能,因为你使用的是 POST。

    要更正此问题,表单标记中的操作必须与 urls.py 中的 url 匹配。

    所以您可以尝试更改您的 HTML:

    <form method="POST" action="/content">
    

    <form method="POST" action="/content/">
    

    或者,您可以更改您的网址:

    url(r'^content/', views.contact, name='content'),
    

    通过删除斜线,并添加行尾正则表达式:

    url(r'^content$', views.contact, name='content'),
    

    只要它们匹配,任何一个都可以。

    【讨论】:

      【解决方案3】:

      据我了解,您想要的行为是这样的:

      1. 用户在其浏览器中访问 /content
      2. 您的 Django 服务器通过渲染 basic.html 进行响应
      3. 用户在表单中输入他们的电子邮件并提交
      4. 表单发布到 /content 并包含一些数据
      5. 服务器使用给定的电子邮件创建一个Email 对象并将其存储在数据库中

      至于错误,请查看 Django 文档中的以下信息:

      APPEND_SLASH

      默认:真

      当设置为 True 时,如果请求 URL 不匹配 URLconf 中的任何模式并且它不以斜杠结尾,则会向附加斜杠的相同 URL 发出 HTTP 重定向。请注意,重定向可能会导致在 POST 请求中提交的任何数据丢失。

      它告诉你在表单操作的末尾添加一个/,就像这样action="/content/",因为在你的urls.py中你指定了url(r'^content/'...

      或者,如果您不想担心所有这些“斜线”业务,请进入您的 settings.py 并添加

      APPEND_SLASH = False
      

      但是,还有更多工作要做。目前,您的 def contact 函数仅处理 GET 请求,并且对于发布某些表单数据时该做什么一无所知。让我们解决这个问题:

      def contact(request):
          if request.method == "GET":
              return render(request, 'personal/basic.html', {'content': ['If you would like more information, leave your email.']})
          
          elif request.method == "POST":  
              email = Email(name=request.POST.get("textfield"))
              email.save()
              return render(request, 'basic.html')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-25
        • 1970-01-01
        • 2017-05-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多