How to test get_success_url in CreateView in Django

334 views
Skip to first unread message

Tony

unread,
Feb 7, 2018, 7:45:45 PM2/7/18
to Django users

I am trying to write a test for the get_success_url method in a CreateView, to make sure it redirects to the newly created page. But the response status code is 200 instead of 302 as I expected.

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’,
                    }
        url = reverse_lazy('blog:blog-create')
        success_url = reverse_lazy('blog:blog-detail', kwargs={'slug':'new-blog'})
response
= self.client.post(url, post) self.assertEqual(response.status_code, 302) self.assertRedirects(response, success_url
)
Reply all
Reply to author
Forward
0 new messages