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

时间:2019-10-20 12:55:52

标签: python html django django-models django-forms

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

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

models.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

forms.py

from .models import modelPost

class testForm(forms.ModelForm):

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

views.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

2 个答案:

答案 0 :(得分:3)

发出了POST请求,您应该在method="post"标签中指定<form>

<form method="post">
    {% 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'检查将失败,因此,它的确会将数据保存到数据库中。

答案 1 :(得分:1)

您需要在form标签中指定方法,method =“ post”,并且在单击Submit或check按钮后,需要在form标签中提供要转到的路径或url。

<form method="post" acton="Enter the path or url here">
    {% 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>

还尝试以表单参数(如testform(request,data = request.POST))传递请求,它现在应该可以正常工作。

相关问题