【问题标题】:Django stops updating data to mysql after page refresh页面刷新后 Django 停止将数据更新到 mysql
【发布时间】:2022-01-25 04:13:45
【问题描述】:

我对使用 django 框架相当陌生,最近我用它制作了一个系统,它通过 html 表单将数据提交到 mysql db。我最终让它工作了,一切看起来都很好,虽然我注意到一个错误,如果我刷新页面 django 停止向 mysql 发送数据,有没有人发生过这种情况?

参考资料:

views.py

from django.shortcuts import render
from websiteDB.models import dbInsert
from django.contrib import messages

def insertToDB(request):
    if request.method == "POST":

        if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
            post = dbInsert()
            post.uname = request.POST.get('uname')
            post.email = request.POST.get('email')
            post.message = request.POST.get('message')
            post.save()
            messages.success(request, "Message sent successfully.")
        return render(request, "contact.html")

    else:
        return render(request, "contact.html")

models.py

from django.db import models

class dbInsert(models.Model):
    uname = models.CharField(max_length=100)
    email = models.EmailField()
    message = models.TextField()
    class Meta:
        db_table = "contactrequest"

urls.py

"""
websiteDB URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from . import views
from . import index

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

   path('homepage', index.page_home, name= 'hpage'),
   path('', views.insertToDB),
   path('contactpage', index.contact_page, name= 'cpage')
]

contact.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@200&display=swap" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'css/css/styles.css' %}">
    <title>Document</title>
</head>
<body style="background-color: rgb(74, 36, 110);">

    <script src="{% static 'js/main.js' %}"></script>

    <div class="top-nav">
        <a href="{% url 'hpage' %}">HOME</a>
        <a href="products.html">PRODUCTS</a>
        <a href="contact.html">CONTACT</a>
        <a href="about.html">ABOUT</a>
        <a href="community.html">COMMUNITY</a>
        </div>

        <div class="div-align">

            <h2>Contact</h2>
            <p>Reach us for questions/concerns through the form below.</p>
        </div>  
    <form class="fontmaker" method="post">
        {% csrf_token %}
        <label for="Username">Username:</label><br>
        <input type="text" id="Username" name="uname" required><br>
        <label for="E-mail">E-mail:</label><br>
        <input type="text" id="Email" name="email" required>
        <label for="Reason" class="margin">Message:</label>
        <textarea id="Reason" name="message" rows="10" cols="60" required>Type your reason of contact here.</textarea>
        <input type="submit" value="Submit" class="rounded-corners" id="submitBtn">

        {% if messages %}
        {% for message in messages %}
            {{message}}
        {% endfor %}
        {% endif %}
        
    </form>
    
</body>
</html>

终端没有错误,按钮点击也正确发送了一个POST请求: Terminal output

我也是在 stackoverflow 上发帖的新手,请告诉我将来发帖时是否还有其他需要改进的地方。

index.py

from django.http import HttpResponse
from django.shortcuts import render

def page_home(request):
    return render(request, 'index.html')

def contact_page(request):
    return render(request, 'contact.html')

提前致谢。

【问题讨论】:

  • 您好,您的请求总是会返回状态 200,因为这部分 return render(request, "contact.html") 不在您的 if 语句中
  • 啊,我明白了,我想这是愚蠢的缩进错误。谢谢你的回答,我去看看我的问题是否解决了。
  • 更新:似乎它仍然没有正确更新到数据库
  • 这不会解决您的问题,因为您的问题是您的表单字段,我强烈建议您使用 django 表单来序列化您的输入,编写代码更安全、更干净。您正在使用 ajax 发送请求吗?
  • 不,我没有使用 ajax,但我会尝试查看 django 表单。

标签: python html mysql django


【解决方案1】:

如果您呈现contactpage/ URL,那么如果您提交表单,您会将其提交到contact 视图,但该视图不处理数据,也不创建任何条目。您必须确保将表单发布到insertToDB 视图。您可以通过为视图命名来做到这一点:

urlpatterns = [
    # …,
    path('', views.insertToDB, name='insertToDB'),
    # …
]

然后在表单中指定端点:

<form class="fontmaker" method="post" action="{% insertToDB %}">
    <!-- … -->
</form>

如果 POST 请求成功,您还应该重定向,例如:

from django.shortcuts import redirect

def insertToDB(request):
    if request.method == 'POST':
        if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
            post = dbInsert.objects.create(
                uname = request.POST['uname'],
                email = request.POST['email'],
                message = request.POST['message']
            )
            messages.success(request, 'Message sent successfully.')
            return redirect('cpage')
        return render(request, 'contact.html')

    else:
        return render(request, 'contact.html')

我建议使用 Django forms [Django-doc],例如 modelform [Django-doc] 来验证和清理表单输入并删除大量样板代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2012-01-08
    • 1970-01-01
    相关资源
    最近更新 更多