python - 数据未使用 Django 表单保存到数据库

标签 python html django django-models django-forms

我正在开发一个包含表单的 Django 应用程序。我定义了模型并进行了迁移。但是数据没有保存到数据库中。当我使用提交表单时,应用程序的 URL 变得困惑。

到目前为止,这是我的代码

模型.py

class modelPost(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField(max_length=70)
    phone = models.CharField(max_length=12)

    def publish(self):
        self.save()

    def __str__(self):
        return self.name

表格.py

from .models import modelPost

class testForm(forms.ModelForm):

    class Meta:
        model = modelPost
        fields = ('name', 'email', 'phone')

View .py

from .forms import testForm

# Create your views here.
def index(request):
    if request.method == "POST":
        testForm = testForm(request.POST)

        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('home')

    else:
        testForm = testForm()
        return render(request, 'index.html', {'testForm': testForm})

index.html

<form>
    {% csrf_token %}
    {{ testForm.name|as_crispy_field }}
    {{ testForm.email|as_crispy_field }}
    {{ testForm.phone|as_crispy_field }}
    <input type="submit" value="check" class="save btn submit_button">
</form>

当我尝试提交表单时,url 发生了这种情况

http://127.0.0.1:8000/?csrfmiddlewaretoken=BG2i7fSbwG1d1cOlLWcEzy5ZQgsNYzMrhDJRarXkR3JyhetpWvqNV48ExY7xM9EW&name=randomPerson&email=test%40test.com&phone=12345678

这些是我检查过的一些链接,但答案不起作用

link1

link2

最佳答案

没有发出 POST 请求,您应该指定 method="post"<form>标签:

<form <b>method="post"</b>>
    {% csrf_token %}
    {{ testForm.name|as_crispy_field }}
    {{ testForm.email|as_crispy_field }}
    {{ testForm.phone|as_crispy_field }}
    <input type="submit" value="check" class="save btn submit_button">
</form>

默认方法是 GET。您实际上可以看到这一点,因为数据是在 URL 的 querystring 中传递的。这因此意味着 request.method == 'POST'检查将失败,因此,它确实不会将数据保存到数据库中。

关于python - 数据未使用 Django 表单保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58473199/

相关文章:

mysql - 为什么 Django 在添加新列时删除 SQL DEFAULT 约束?

python - 尽管安装了 Ansible,但找不到 boto3 和 botocore

python - 修改flask中的MongoDB数据

python - 在python中多次使用数组内部的 'range'

javascript - Google Chrome/Chromium/Webkit 的隐藏 API

django - 我应该如何为使用 South 的 Django 应用程序设置 SOUTH_DATABASE_ADAPTERS?

python - 在 PyCharm 中设置虚拟环境

html - 媒体查询在 Chrome 中不起作用,在 Firefox 中有效

html - 使用 flex 和 border-box 等宽

jquery - 如何访问views.py中ajax调用发送的数据 python django