django 未找到没有参数的“new_url”的NoReverseMatch at / Reverse,已尝试1种模式:['new/(?P< spk>[0-9]+)/\\Z']

kb5ga3dv  于 2023-05-01  发布在  Go
关注(0)|答案(1)|浏览(131)

无法解决此错误。其想法是,用户填写的表单后,通过PK进入页面,他输入的数据所在的位置

  • views.py*
# Form
class GetUser(FormView):
    form_class = PersonForm
    success_url = reverse_lazy('new_url')
    template_name = 'party/home.html'

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            form = PersonForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data

                pc = Person(name=cd.get('name'), last_name=cd.get('last_name'))
                pc.save()
        return redirect(self.success_url)

# DetailView
class UserNew(DetailView):
    model = Person
    template_name = 'party/show.html'
    context_object_name = 'new_user'

    def get_queryset(self):
        return Person.objects.filter(pk=self.kwargs['pk'])
  • models.py*
class Person(models.Model):
    name = models.CharField(max_length=150, verbose_name='Імʼя')
    last_name = models.CharField(max_length=150, verbose_name='Прізвище')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='created_at')

    def __str__(self):
        return f'{self.name} {self.last_name}'

    def get_absolute_url(self):
        return reverse('person', kwargs={'pk': self.pk})

    class Meta:
        verbose_name = 'Person'
        verbose_name_plural = 'Person'
        ordering = ['-created_at']
  • html*
<body>
    <div>
        <h1>Привіт</h1>
    </div>

    <form action="{% url 'home_url' %}" method="post">
        {% csrf_token %}
        {{ form.as_p }}

        <button type="submit" class="btn btn-primary btn-block">Let`s go</button>
    </form>

</body>
  • url.py*
urlpatterns = [
    # path('', get_user, name='home_url'),
    path('', GetUser.as_view(), name='home_url'),
    path('all', UserAll.as_view(), name='all_url'),
    path('new/<int:pk>/', UserNew.as_view(), name='new_url'),
]

我试着重写 www.example.com , www.example.com ,但什么都不管用

smdncfj3

smdncfj31#

错误正在发生,因为在您的url中,您已经定义了它将有额外的参数,可能像这样

path('new/<int:pk>', SomeView.as_view(), name='new_url')

因此,url应该看起来像localhost:8000/new/123。但是当你使用reverse_lazy时,你没有传递参数(spk值),因此它导致了这个问题。但你可以这样修复它:

class GetUser(FormView):
    form_class = PersonForm
    template_name = 'party/home.html'

    def form_valid(self, form):
        cleaned_data = form.cleaned_data
        person = Person(name=cd.get('name'), last_name=cd.get('last_name'))
        person.save()
        return redirect('new_url', spk=person.pk)

更多信息可以在文档中找到。

相关问题