M
M
marselabdullin2020-08-14 16:30:22
Django
marselabdullin, 2020-08-14 16:30:22

Why is there a circular dependency of django imports?

I am getting an error:

cannot import name 'Device' from partially initialized module 'cms.models' (most likely due to a circular import)

I found out that it is related to the circular import of validators:
from django.core.validators import MaxValueValidator, MinValueValidator
from .validators import UniversalMaxValidator, UniversalMinValidator

An example of using these validators in a model:
height = models.FloatField(validators=[UniversalMinValidator(metric_min=50, inch_min=1.8).validate(), UniversalMaxValidator(metric_max=260, inch_max=8.7).validate()], verbose_name=_('height'),
                               help_text=None, default=0, error_messages={'required': _('Indicate your height')})
    weight = models.FloatField(validators=[MinValueValidator(20), MaxValueValidator(1330)], verbose_name=_('weight'),
                               help_text=None, default=0, error_messages={'required': _('Enter your weight')})


validators.py (from which I import custom validators):
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator, BaseValidator
from django.utils.translation import gettext_lazy as _

from .views import HealthData


class UniversalMinValidator(BaseValidator):
    def __init__(self, metric_min, inch_min):
        self.metric_min = metric_min
        self.inch_min = inch_min
        self.measuring_system = self.request.user.health_data.measuring_system

    def validate(self):
        if self.measuring_system == 'Metric':
            return MinValueValidator(self.metric_min)
        else:
            return MinValueValidator(self.inch_min)


class UniversalMaxValidator(BaseValidator):
    def __init__(self, metric_max, inch_max):
        self.metric_min = metric_max
        self.inch_min = inch_max
        self.measuring_system = self.request.user.health_data.measuring_system

    def validate(self):
        if self.measuring_system == 'Metric':
            return MinValueValidator(self.metric_max)
        else:
            return MinValueValidator(self.inch_max)

When I remove the import of the custom validator, everything works, but I need to use it so that the validator is converted depending on the selected calculus

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cython, 2020-08-14
@marselabdullin

Remove line 5 from validators.py. It turns out that you are importing validators into views, and views into validators, although the purpose of this import is not clear.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question