无法将数据发送到 Django 中的数据库

Unable to send data to database in Django

我是 Django 开发的绝对初学者,我无法通过 POST 方法将数据发送到我的数据库。请指导我的方法有什么问题。我的模型运行完美,现在我可以在我的 Django 管理员上访问我想要的 table。我在 views.py 中创建的函数始终执行 else 条件。

来自 views.py:

from django.shortcuts import render, HttpResponse, redirect
from app.models import Tbl_Feedback

def myform(request):
    return render(request, 'form.html')
def getfeedback(request):
    if request == "POST":
        a = request.POST.get('a')
        objTbl_Feedback = Tbl_Feedback(a="a")
        objTbl_Feedback.save()
        return redirect("/")
    else:
        return HttpResponse('Form Not Submitted')

来自 models.py:

from django.db import models

# Create your models here.

class Tbl_Feedback(models.Model):
    fdbk = models.CharField(max_length=120)
    

来自 urls.py(app):

from django.contrib import admin
from django.urls import path
from app import views

urlpatterns = [
    
    path('',views.myform,name="form"),
    path('getfeedback', views.getfeedback, name="feedback")
]

来自 urls.py(项目):

 from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path("", include("app.urls"))
    ]

    

Html:

<!DOCTYPE html>
<html lang="en">
    {% load static %}
<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">
    <title>Form</title>
    {% load static %}
    <link rel="stylesheet" href="{%static 'css.css'%}">

</head>
<body>
    <form action="getfeedback" method="post" >
        {% csrf_token %}
        <div class="frame">
            <div class="frame-header">FeedBack Please !</div>
            <div class="frame-body">
                <div class="form-element">
                    <div class="element-label"><label for="a">FeedBack</label></div>
                    <div class="element-controller">
                        
                        <textarea name="a" id="a" cols="30" rows="5" class="controller-input"
                        autofocus="autofocus" maxlength="120"></textarea>
                    </div>
                </div>
                
            </div>
            <div class="frame-footer"><button type="submit">Submit</button> </div>
        </div>

    </form>

    
</body>

</html>

在您的 getfeedback 视图中有两个问题。

  1. 你需要写if request.method == 'POST':
  2. “a”不是您模型中的字段
def getfeedback(request):
    if request.method == "POST":
        a = request.POST.get('a')
        objTbl_Feedback = Tbl_Feedback(fdbk="a")
        objTbl_Feedback.save()
        return redirect("/")
    else:
        return HttpResponse('Form Not Submitted')