gpt4 book ai didi

django - 如何在 Django 的 CreateView 中测试 get_success_url

转载 作者:行者123 更新时间:2023-12-05 07:37:20 24 4
gpt4 key购买 nike

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

View .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

配置/urls.py

from django.conf.urls import include, url

urlpatterns = [
url(r'^blog/', include('blog.url', namespace='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'),
]

测试.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/‘)

最佳答案

您是否尝试在测试中执行 client.post()

/blog/new/ 中删除尾部斜线

关于django - 如何在 Django 的 CreateView 中测试 get_success_url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48635503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com