首页 > 解决方案 > 为什么这个 url 在 Django 上没有被反向解析?

问题描述

我有一个更新条目的方法:

@require_POST
def update(request, uuid):
    posti = get_object_or_404(Post, uuid=uuid)
    f = PostForm(request.POST)
    if f.is_valid():
        posti.title = request.POST['title']
        posti.text = request.POST['text']
        posti.save()
        return HttpResponseRedirect(django.urls.reverse('posti:detail', args=(posti.uuid,)))
    else:
        messages.error(request, "No title in form")
        return render(request, 'posti/detail.html', {'form': f})

我正在尝试用一个案例来测试这个方法:

def create_post():
    """

    :rtype : Post
    """
    data = {'title': 'Esto es un titulo', 'text': 'Esto es un texto de prueba'}
    post = Post.create_post(data['title'], data['text'])
    post.save()
    print('The UUID is: ', post.uuid)
    return post

def test_updating_post_with_no_title(self):
        """
        A post with no title should not be saved
        :return:
        """
        p = create_post()
        print('(test) The UUID is: ', p.uuid)
        data = {'title': '', 'text': 'Esto es un texto de prueba'}
        url = reverse('posti:update', args=(p.uuid,))
        response = self.client.post(url, data, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No title in form")

无论我做什么,我总是会得到这个错误:

django.urls.exceptions.NoReverseMatch:没有找到带有参数“(”,)“的“更新”的反向。尝试了 1 种模式:['posti/update/(?P[0-9a-zA-Z-_]+)/$']

UUID 确实出现在使用print(p.uuid)这两种方法的测试中,但它没有到达从下到上的第四行。它说“未找到参数'('',)'”的地方应该出现一个UUID。为什么不显示它?

编辑:UUID 是 SmallUUID。我不知道这是否有问题。

标签: djangodjango-urls

解决方案


推荐阅读