1 回答

TA贡献1783条经验 获得超4个赞
你views.py有点偏离 - 你没有在任何地方呈现你的表单。我起草了一个快速应用程序(我认为它可以满足您的需求) - 如果它有效,请告诉我:
主/模板/index.html
在这里,我只是将表单的操作设置为""(这就是您所需要的)并取消注释该form.as_p行
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Form 1</title>
</head>
<body>
<form action="" method="post" autocomplete="off">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Send message">
</form>
</body>
</html>
主/views.py
请注意这里的差异,我们正在测试请求类型并根据传入的请求类型采取适当的措施。如果是 POST 请求,我们将处理表单数据并保存到数据库中。如果没有,我们需要显示一个空白表格供用户填写。
from django.shortcuts import render, redirect
from .forms import HomeForm
def insert_my_num(request):
# Check if this is a POST request
if request.method == 'POST':
# Create an instance of HomeForm and populate with the request data
form = HomeForm(request.POST)
# Check if it is valid
if form.is_valid():
# Process the form data - here we're just saving to the database
form.save()
# Redirect back to the same view (normally you'd redirect to a success page or something)
return redirect('insert_my_num')
# If this isn't a POST request, create a blank form
else:
form = HomeForm()
# Render the form
return render(request, 'index.html', {'form': form})
让我知道这是否有效!
添加回答
举报