Presently I’m testing only one app for which I have nested a package dedicated to separating my tests ( test_models.py
, test_forms.py
, etc.). When I created my test_forms.py module and attempted to run python manage.py test, I get an ImportError
& ValueError
. How can I fix this so my test modules run without raising these errors? My file structure is also attached.
ImportError: Failed to import test module: photos.test.test_forms
Traceback (most recent call last):
File “C:…\lib\unittest\loader.py”, line 436, in _find_test_path
module = self._get_module_from_name(name)
File “C:…\lib\unittest\loader.py”, line 377, in _get_module_from_name
import(name)
File “C:…\django_photo_app\photos\test\test_forms.py”,
line 2,in
from …forms import PhotoForm
File “C:…\django_photo_app\photos\form.py”,
line 8, in
from …models import Photo
ValueError: attempted relative import beyond top-level package
There’s not really much for us to go on without the code. From what I can see, the error is occurring on line 2 of test_forms.py. If it’s an ImportError
, my best guess is that you’re incorrectly importing the module on line 2.
Here’s is my models.py
and forms.py
:
import os
from django import forms
from django.core.exceptions import ValidationError
from django.core.files.storage import get_storage_class
from ..models import Photo
def validate_title(value):
if not value:
raise ValidationError("Must provide image title")
class PhotoForm(forms.ModelForm):
storage = forms.CharField(validators=[validate_title])
class Meta:
model = Photo
fields = ["storage", "title"]
def clean_source(self):
storage = get_storage_class()
if storage.get_valid_name(self.cleaned_data["source"]):
raise ValidationError("File is already saved.")
return self.cleaned_data["source"]
from django.db import models
from django.conf import settings
# Create your models here.
class Photo(models.Model):
source = models.ImageField(upload_to='uploads/%Y/%m/%d/')
title = models.CharField(max_length=50)
upload_date = models.DateField(auto_now_add=True)
likes = models.IntegerField(default=0)
photographer = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
def __str__(self):
return self.title
Unless I’m misunderstanding something here, that line should be:
from .models import Photo
(one period, not two)