代码之家  ›  专栏  ›  技术社区  ›  Back2Basics

django cookiecutter媒体/测试位置

  •  0
  • Back2Basics  · 技术社区  · 3 年前

    问题:我在模型中有一个ImageField。TestCase无法找到默认的图像文件来对其执行图像大小调整(一个@receiver(pre_save,sender=UserProfile)decorator之类的东西)

    class UserProfile(Model):
        user = ForeignKey(AUTH_USER_MODEL ...)
        ...
        photo = ImageField(
            verbose_name=_("Photo"),
            upload_to="media",
            null=True,
            blank=True,
            help_text=_("a photo will spark recognition from others."),
            default="default.png")
    

    概述:我在本地运行从pycharm到docker容器的测试。这个项目是基于django cookiecutter项目。

    我在预售挂钩中搜索了目标文件,在这两个目录中找到了该文件[“/app/media/default.png”,“/opt/project/media/default.png'”]

    我在'/app/<my_project_name>/media/default.png'

    如何在这些目录中查找媒体文件?

    @receiver(pre_save, sender=UserProfile)
    def user_profile_face_photo_reduction(sender, instance, *args, **kwargs):
        """
        This creates the thumbnail photo for a concept
        """
    
        test_image_size(instance) # this is the function that gives problems.  it's below.
        im = generic_resize_image(size=face_dimensions, image=instance.photo)
        save_images_as_filename(
            filename=Path(instance.photo.path).with_suffix(".png"),
            image=im,
            instance=instance,
        ) 
    
    
    def test_image_size(instance=None, size_limit=None):
        """
        size_limit is a namedtuple with a height and width that is too large to save.
        instance needs to have a photo attribute to work
        """
        if instance and instance.photo:
            print([x.absolute() for x in sorted(Path("/").rglob("default.png"))]) # this is where I got the actual location info
            assert instance.photo.size <= 10_000_000, ValueError("Image size is too big") # THE PROBLEM LINE IS THIS ONE.
            if (
                instance.photo.width > size_limit.width
                or instance.photo.height > size_limit.height
            ):
                raise ValueError(_("the picture dimensions are too big"))
    
    0 回复  |  直到 3 年前
        1
  •  1
  •   Dharman Aman Gojariya    3 年前
    1. 您是否已将主机的媒体卷装载到dockerfile?您可能需要向我们展示dockerfile,以便我们更好地了解您的配置。

    2. 如果直接在主机上使用文件夹运行测试不是硬性要求,那么您可以在Django项目根文件夹中创建另一个文件夹(即“testmedia”)。在tests.py文件中,您可以覆盖测试的媒体根设置以使用“testmedia”文件夹。将测试图像文件放在文件夹中。以下是覆盖媒体根设置的示例:

      TEST_DIR = os.path.join(settings.BASE_DIR, 'testmedia/') #Defines test media root
      
      @override_settings(MEDIA_ROOT=(TEST_DIR))
      def test_create_blogpost(self):
       print("\nTesting blog post creation...")
      
       testUser = User.objects.create_user(username='testUser', password='12345') #Creates test user
       self.client.login(username='testuser', password='12345') #Logs in testUser
      
       PNGtestpic = SimpleUploadedFile(name="pngtest.png", content=open(settings.MEDIA_ROOT + "pngtest.png", 'rb').read(), content_type='image/png') #Uploads test picture to media root
       Blogpost.objects.create(title="How to run tests", cover_image= PNGtestpic, author=testUser)
      
        2
  •  1
  •   Back2Basics    3 年前

    我开始在app_root文件夹(/Users//<project_name>/)中创建一个“媒体”目录。这是一个愚蠢的举动。(/Users//<project_name>//<项目名称>/media)文件夹中已经有一个我没有看到的媒体文件夹。我试图使用docker挂载技巧和更改代码之类的技巧来强迫它,这是浪费时间。

    我投票支持@heyylatef对override_settings的回答,因为这是一个巧妙的装饰器。