django cookiecutter 媒体/测试位置

django cookiecutter media/ location for testing

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

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//media/default.png”上收到 FileNotFound 错误

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

@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"))
  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)
    

我开始在 app_root 文件夹 (/Users///) 中创建一个“媒体”目录。那是一个愚蠢的举动。 (/Users////media) 文件夹中已经有一个我没有看到的媒体文件夹。我试图使用 docker 安装技巧和更改我的代码等技巧来强制它,这是浪费时间。

我赞成@heyylateef 对 override_settings 的回答,因为它是一个简洁的装饰器。