如何在Django的CreateView中测试get_success_url函数

3

我正在尝试为CreateView中的get_success_url方法编写测试,以确保它重定向到新创建的页面。但是响应状态代码是405,而不是我预期的302。

views.py

class BlogCreate(CreateView):
    model = Blog
    fields = [‘author’, 'title', ’post’]
    def get_success_url(self):
        return reverse_lazy('blog:blog-detail', kwargs={'slug': self.object.slug})

class BlogList(ListView):
    model = Blog
    ordering = ["-created"]


class BlogDetail(DetailView):
    model = Blog

config/urls.py

from django.conf.urls import include, url

urlpatterns = [
    url(r'^blog/', include('blog.url', namespace='blog')),

blog/urls.py

from django.conf.urls import url
from .views import BlogCreate, BlogList, BlogDetail, BlogEdit, BlogDelete


urlpatterns = [
    url(r'^(?P<slug>[-\w]+)/$', BlogDetail.as_view(), name='blog-detail'),
    url(r'^(?P<slug>[-\w]+)/edit$', BlogEdit.as_view(), name='blog-edit'),
    url(r'^(?P<slug>[-\w]+)/delete$', BlogDelete.as_view(), name='blog-delete'),
    url(r'^new$', BlogCreate.as_view(), name='blog-create'),
    url(r'^$', BlogList.as_view(), name='blog-list'),
]

tests.py

class BlogCreateTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='john', password='123')

    def test_create_success_url(self):
        post = {‘author’: self.user,
                'title': ‘new blog’,
                ‘article’: ‘text’,
                    }
        response = self.client.post('/blog/new/', post)

        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, 'blog/new-blog/‘)

请展示您的urls.py文件。 - Exprator
创建后,你的网络浏览器会前往哪个URL? - Ykh
创建后,应该使用新创建对象的slug前往“blog-detail”。它已经在浏览器中工作了,但在我的测试中不起作用。 - Tony Foy
你找到解决方案了吗? - Aseem
1个回答

0
你是否在测试中尝试执行client.post()操作?
请从/blog/new/中删除末尾的斜杠。

由于某些原因,您的视图仅允许使用 GET 方法。也许您已经在视图上使用了一些装饰器以仅允许 GET 方法? 该错误意味着在特定视图“BlogDetail”上不允许使用 POST 方法。 - unixia
不,我没有。我已经更新了我的帖子,包括views.py。 - Tony Foy
已更新我的回答,请检查。 - unixia
1
谢谢,那很有帮助。但现在我得到的是200而不是302。当我执行self.assertEqual(Blog.objects.all().count(),1)时,它没有创建任何新条目。 - Tony Foy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接