我正在尝试制作一个django网络应用程序,该应用程序具有一种形式,要求用户输入电话号码并将该号码存储在postgres数据库中。以下代码给了我错误:
/ main / insert_num /处的NoReverseMatch
找不到与“相反的符号。 ”不是有效的视图函数或模式名称。
而且我不知道问题出在哪里,有人可以帮忙吗?
index.html
<html lang="en">
<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="{% url 'insert_my_num' %}" method="post" autocomplete="off">
{% csrf_token %}
<!-- {{ form.as_p }} -->
<input type="submit" value="Send message">
</form>
</body>
</html>
forms.py
from django import forms
from phone_field import PhoneField
from main.models import Post
class HomeForm(forms.ModelForm):
phone = PhoneField()
class Meta:
model = Post
fields = ('phone',)
models.py
from django.db import models
from phone_field import PhoneField
class Post(models.Model):
phone = PhoneField()
main / urls.py
from django.urls import path
from . import views
urlpatterns = [
path('insert_num/', views.insert_my_num,name='insert_my_num')
]
project / urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('main/',include('main.urls'))
]
views.py
def insert_my_num(request: HttpRequest):
phone = Post(request.POST.get('phone'))
phone.save()
return redirect('')
您的views.py
有点差-您不会在任何地方渲染表单。我草拟了一个快速应用程序(我认为它可以满足您的需求)-让我知道是否可行:
main / templates / index.html
[这里,我只是将表单的动作设置为""
(这是您在这里所需要的全部,而未注释form.as_p
行]
<html lang="en">
<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>
main / 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})
让我知道是否可行!