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})
讓我知道這是否有效!
添加回答
舉報