我正在开发一个包含表单的 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
这些是我检查过的一些链接,但答案不起作用
最佳答案
您没有发出 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/