• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

카테고리의 slug를 수정하면 301에러가 발생합니다.

20.11.23 17:10 작성 조회수 193

0

21:04에서처럼

def create_category(name='life', description=''):
    ....
    category.slug = category.name.replace(' ', '-').replace('/', '')
    category.save()
    ....

를 했더니 테스트에서 301 에러가 발생합니다. 

Traceback (most recent call last):

  File "C:\Users\msra9\python_projects\django_my_website\blog\tests.py", line 200, in test_post_list_by_category

    self.assertEqual(response.status_code, 200)

AssertionError: 301 != 200

cmder에서는 에러 설명이 이것뿐이라서 뭐가 문제인건지 모르겠습니다..

답변 4

·

답변을 작성해보세요.

1

혹시, 저에게 보여주지 않은 modes.py의 Category 클래스에 get_absolute_url에서 슬래시를 마지막에 빠뜨리시지 않았나요?

한참을 고민해봤는데, 그게 문제이지 않을까 싶네요?

def get_absolute_url(self):
return '/blog/category/{}/'.format(self.slug)

라고 작성해야 하는데

def get_absolute_url(self):
return '/blog/category/{}'.format(self.slug)

라고 만드신게 아닌가 싶어요.

0

선생님 말씀이 맞네요..

슬래시를 추가했더니 해결됬습니다.

이것때문에 이틀내내 끙끙댔는데.. 해결되서 속이 시원하네요.

정말 감사합니다!

0

테스트코드는

def test_post_list_by_category(self):
# 카테고리를 생성한다.
category_politics = create_category(name='정치/사회')
self.assertGreater(Category.objects.count(), 0)

# 포스트를 생성한다.
post_000 = create_post(
title='the first post',
content='hello world',
author=self.author_000
)
post_001 = create_post(
title='the second post',
content='goodbye world',
author=self.author_000,
category=category_politics
)
self.assertGreater(Post.objects.count(), 0)

# /blog/category/slug/에 접근을 시도하고 성공여부를 확인한다.
response = self.client.get(category_politics.get_absolute_url())
self.assertEqual(response.status_code, 200)

soup = BeautifulSoup(response.content, 'html.parser')

# 페이지 타이틀 태그를 확인한다.
self.assertEqual(soup.title.text, 'Blog - {}'.format(category_politics.name))

# 네비게이션에 Blog, About Me가 있는지 확인한다.
self.check_navbar(soup)

# 미분류 뱃지는 없고, 정치/사회 뱃지만 있는지 확인한다.
main_div = soup.body.find('div', id='main_div')
self.assertNotIn('미분류', main_div.text)
self.assertIn(category_politics.name, main_div.text)

views.py는

class PostList(ListView):
model = Post

def get_queryset(self):
return Post.objects.order_by('-created')

def get_context_data(self, *, object_list=None, **kwargs):
context = super(PostList, self).get_context_data(**kwargs)
context['category_list'] = Category.objects.all()
context['posts_without_category'] = Post.objects.filter(category=None).count()
return context


class PostDetail(DetailView):
model = Post

def get_context_data(self, *, object_list=None, **kwargs):
context = super(PostDetail, self).get_context_data(**kwargs)
context['category_list'] = Category.objects.all()
context['posts_without_category'] = Post.objects.filter(category=None).count()
return context


class PostListByCategory(PostList):
def get_queryset(self):
slug = self.kwargs['slug']
category = Category.objects.get(slug=slug)
return Post.objects.filter(category=category).order_by('-created')

blog/urls.py는 

from django.urls import path
from . import views


urlpatterns = [
path('category/<str:slug>/', views.PostListByCategory.as_view()),
path('<int:pk>/', views.PostDetail.as_view()),
path('', views.PostList.as_view())
]

입니다.

0

혹시 테스트코드와 views.py, urls.py도 보여주실 수 있나요?