我正在尝试测试内部共享Python软件包中没有django 设置文件的自定义字段(因为没有django应用)。运行测试时,出现以下错误。
tests/test_fields.py:3: in <module>
from rest_framework.validators import ValidationError
../../../.virtualenvs/myenv/lib/python3.6/site-packages/rest_framework/validators.py:14: in <module>
from rest_framework.compat import unicode_to_repr
../../../.virtualenvs/myenv/lib/python3.6/site-packages/rest_framework/compat.py:107: in <module>
from django.contrib.postgres import fields as postgres_fields
../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/postgres/fields/__init__.py:1: in <module>
from .array import * # NOQA
../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/postgres/fields/array.py:3: in <module>
from django.contrib.postgres import lookups
../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/postgres/lookups.py:4: in <module>
from .search import SearchVector, SearchVectorExact, SearchVectorField
../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/postgres/search.py:47: in <module>
class SearchVector(SearchVectorCombinable, Func):
../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/postgres/search.py:50: in SearchVector
_output_field = SearchVectorField()
../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:172: in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/conf/__init__.py:56: in __getattr__
self._setup(name)
../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/conf/__init__.py:39: in _setup
% (desc, ENVIRONMENT_VARIABLE))
E django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
是否有抑制加载设置的需求?我只是试图测试该字段的逻辑。
class FMIDField(Field):
VALID_CHARS = '[a-zA-Z0-9]{8}'
default_error_messages = {
'invalid_type': 'FMID must be a string',
'invalid_characters': 'FMID must be 8 characters long and consist only of a-z, A-Z and 0-9'
}
def is_valid_chars(self, data):
prog = re.compile(self.VALID_CHARS)
return prog.fullmatch(data)
def to_internal_value(self, data):
if not isinstance(data, str):
self.fail('invalid_type')
if not self.is_valid_chars(data):
self.fail('invalid_characters')
return data
def to_representation(self, value):
return value
编辑为清楚起见
正在编写和测试的python软件包没有Django设置模块,因为它应该在Django应用程序中使用。
答案 0 :(得分:0)
您应在文件中包含以下行
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PROJECT_NAME.settings")
django.setup()
编辑
尝试this指南