inflearn logo
강의

Khóa học

Chia sẻ kiến thức

Giới thiệu về phát triển web cho người dùng Python từ A đến Z Django + Bootstrap

test.py 오류

732

woody

7 câu hỏi đã được viết

0

test.py 를 하면 

raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)

ValueError: The 'image' attribute has no file associated with it.

위와 같은 에러가 나옵니다.

*test.py 참고

from django.test import TestCase, Client
from bs4 import BeautifulSoup
from .models import Post, Category, Tag
from django.utils import timezone
from django.contrib.auth.models import User


def create_category(name='대외활동'description=''):
    category, is_created = Category.objects.get_or_create(
        name=name,
        description=description,
    )

    category.slug = category.name.replace('''-').replace('/''')
    category.save()

    return category


def create_tag(name='some tag'):
    tag, is_created = Tag.objects.get_or_create(
        name=name,
    )
    tag.slug = tag.name.replace('''-').replace('/''')
    tag.save()

    return tag


def create_post(titleorganizationauthorlinkcategory=None):
    blog_post = Post.objects.create(
        category=category,
        title=title,
        organization=organization,
        birthline=timezone.now(),
        deadline=timezone.now(),
        link=link,
        author=author,
        created=timezone.now(),
        updated=timezone.now(),
    )

    return blog_post


class TestModel(TestCase):
    def setUp(self):
        self.client = Client()
        self.author_000 = User.objects.create(
            username='westline'password='nopassword')

    def test_category(self):
        category = create_category()

        post_000 = create_post(
            title='The first post',
            organization='SK',
            link='https://www.naver.com',
            author=self.author_000,
            category=category,
        )

        self.assertEqual(category.post_set.count(), 1)

    def test_tag(self):
        tag_000 = create_tag(name='bad_guy')
        tag_001 = create_tag(name='america')

        post_000 = create_post(
            title='The first post',
            organization='SK',
            link='https://www.naver.com',
            author=self.author_000,
        )

        post_000.tags.add(tag_000)
        post_000.tags.add(tag_001)
        post_000.save()

        post_001 = create_post(
            title='The second post',
            organization='Samsung',
            link='https://www.naver.com',
            author=self.author_000,
        )

        post_001.tags.add(tag_001)
        post_001.save()

        self.assertEqual(post_000.tags.count(), 2)  # post는 여러개의 tag를 가질 수 있다.
        # 하나의 tag는 여러개의 post에 붙을 수 있다
        self.assertEqual(tag_001.post_set.count(), 2)
        self.assertEqual(tag_001.post_set.first(), post_000)
        # 하나의 tag는 자신으 가진 post들을 불러올 수 있다.
        self.assertEqual(tag_001.post_set.last(), post_001)

    def test_post(self):
        category = create_category()
        post_000 = create_post(
            title='The first post',
            organization='SK',
            link='https://www.naver.com',
            author=self.author_000,
            category=category,
        )


class TestView(TestCase):
    def setUp(self):
        self.client = Client()
        self.author_000 = User.objects.create(
            username='westline'password='nopassword')

    def test_post_list_no_post(self):
        response = self.client.get('/blog/')
        self.assertEqual(response.status_code, 200)

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

        self.assertIn(title.text, '대외활동의 모든 것')

        self.assertEqual(Post.objects.count(), 0)
        self.assertIn('아직 게시물이 없습니다.', soup.body.text)

    def test_post_list_with_post(self):
        post_000 = create_post(
            title='The first post',
            organization='SK',
            link='https://www.naver.com',
            author=self.author_000,
        )

        post_001 = create_post(
            title='The second post',
            organization='SAMSUNG',
            link='https://www.daum.net',
            author=self.author_000,
        )

        self.assertGreater(Post.objects.count(), 0)

        response = self.client.get('/blog/')
        self.assertEqual(response.status_code, 200)
        soup = BeautifulSoup(response.content, 'html.parser')
        body = soup.body
        self.assertNotIn('아직 게시물이 없습니다.', body.text)
        self.assertIn(post_000.title, body.text)

bootstrap django python

Câu trả lời 2

0

woody

감사합니다! 맞습니다 강의보면서 공부하고 적용시켜보고있지만 쉽지않네요ㅠㅠ

0

SungYong Lee

제 강좌에서 약간 변형한 내용으로 웹사이트를 만들고 계신 것 같습니다. 

에러메세지 내용은 image 필드에 파일이 채워져야 한다는 뜻입니다. 어떤 모델인지 알 수 없으나, 그 모델에 image라는 이름의 필드를 만드신 것 같습니다. image 필드에blank=True, null=True 가 선언되어 있지 않아 무조건 채워져야 하는 것으로 되어 있어서 저런 메세지가 나오는 것이 아닐까 싶네요. 

해결방안은 models.py를 열어서 image 필드에 blank=True, null=True를 추가해주시고, 마이그레이션 하시면 될 것 같습니다. 

후속 강의

0

390

1

완성했습니다. 감사합니다

0

321

2

오늘 vps 에 domain 을 지정해주고 아직 활성화되지 않았는데

0

299

1

test 결과 두 가지 error 가 발생했습니다. 뭐가 잘못된 건지 도저히 모르겠습니다.

0

421

1

accounts/login 이 존재하지 않는다고 나옵니다

0

269

2

코드 질문입니다

0

248

1

포스트에 markdown을 사용해서 이미지를 추가할때

0

311

1

New Post 관련 질문드립니다.

0

179

1

이번 영상부터 각 포스트에 프리뷰 사진이 달라지셔서 질문 드립니다.

0

335

1

base 작업한 후 Category가 블로그 하단으로 내려갔습니다.

0

254

1

혹시 소스코드 전체가 담긴 주소를 좀 알 수 있을까요?

0

265

1

9분 경 테스트에서 Assretion Error가 발생합니다.

0

235

1

파이참 초기 설치 후 설정 관련해서 git에 항상 add되는 옵션을 체크했습니다.

0

345

3

F12를 눌러 console 창에서 오류를 확인할때 몇번째 줄인지 나오지 않습니다.

0

396

1

post view도 delete하려는데 막혀서 ㅠㅠ

0

197

1

"GET / HTTP/1.1" 400 143 그리고 "GET / HTTP/1.1" 404 2031

0

3304

3

연결이 안됩니다

0

506

8

서버에 연결하고 나면 그 후에 Cmder가 작동이 안되요

0

378

2

서버에 배포후 어드민계정

0

590

2

안녕하세요! 실서버에 올린 sqlite3의 데이터를 직접 확인하려면 어찌하나요?

0

2039

3

gitignore안먹히는현상

0

292

1

cmder 종료시 서버도 같이 종료됩니다.

0

220

1

' python manage.py makemigration blog ' 명령어 에러

0

588

2

python manage.py makemigrations 를 했을 때 오류가 납니다.

0

560

2