/main/insert_num/ Django 的 NoReverseMatch

NoReverseMatch at /main/insert_num/ Django

我正在尝试制作一个 django 网络应用程序,它有一个表单,要求用户输入一个 phone 数字并将该数字存储在 postgres 数据库中。以下代码给我错误:

NoReverseMatch at /main/insert_num/

Reverse for '' not found. '' is not a valid view function or pattern name.

我不知道问题出在哪里,有人可以帮忙吗?

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})

如果可行,请告诉我!