python - Django 导入错误 : cannot import name 'x'

标签 python django django-models

我的两个文件中存在循环问题。创建对象时运行模型导入函数,此函数导入模型以检查代码是否唯一。

如何在函数中使用模型,在模型中使用函数而不存在循环问题?我检查了与我的问题类似的问题,但我仍然不知道如何解决这个问题。

模型.py

from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from .middleware.current_user import get_current_user
from shortener.utils import create_shortcode
from django.conf import settings
CODE_MAX_LENGTH = getattr(settings, 'CODE_MAX_LENGTH', 16)


class Shortener(models.Model):
    url = models.URLField()
    code = models.CharField(unique=True, blank=True, max_length=CODE_MAX_LENGTH)
    author = models.ForeignKey(User, blank=True, null=True)  # Allow anonymous
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True)

    def save(self, *args, **kwargs):
        if not self.pk:
            self.author = get_current_user()

            if self.code in [None, ""]:
                self.code = create_shortcode()
            elif self.code.find(' ') != -1:
                self.code = self.code.replace(' ', '_')

            if self.url not in ["http", "https"]:
                self.url = "http://{0}".format(self.url)

        super(Shortener, self).save(*args, **kwargs)

    def __str__(self):
        return self.url

    def __unicode__(self):
        return self.url

    def get_short_url(self):
        return reverse("redirect", kwargs={'code': self.code})

实用程序.py

import random
import string
from django.conf import settings
from shortener.models import Shortener
SIZE = getattr(settings, 'CODE_GENERATOR_MAX_SIZE', 12)


def code_generator(size=SIZE):
    return ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(size))


def create_shortcode():
    code = code_generator()

    if Shortener.objects.filter(code=code).exists():
        create_shortcode()

    return code

回溯:

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x037EAB28>
Traceback (most recent call last):
  File "C:\Users\loc\shortener\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\loc\shortener\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\loc\shortener\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Users\loc\shortener\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\loc\shortener\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\loc\shortener\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\loc\shortener\lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "C:\Users\loc\shortener\lib\site-packages\django\apps\config.py", line 199, in import_models
    self.models_module = import_module(models_module_name)
  File "E:\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "C:\Users\loc\PycharmProjects\DjangoURLShortener\shortener\models.py", line 4, in <module>
    from shortener.utils import create_shortcode
  File "C:\Users\loc\PycharmProjects\DjangoURLShortener\shortener\utils.py", line 4, in <module>
    from shortener.models import Shortener
ImportError: cannot import name 'Shortener'

最佳答案

简答:将create_shortcode 实现移动到models.py 模块中,只需 3 行代码即可在其中生成代码,你避免循环进口。使用 self.objects.filter(...) 在模型和 Shortener.save 方法中执行过滤器。

更长的答案:uuid 模块和 uuid.uuid4 函数(比自己编写可能有错误的实现)更好地生成唯一代码。目前,您正在生成 12 个字符或 12 个字节的随机代码,而 UUID 模块可以开箱即用地为您生成 16 个字节的代码。如果您想启用用户可定义或可覆盖的代码,但希望自动生成非常独特的代码:

code = models.CharField(unique=True, max_length=16, default=uuid.uuid4)

关于python - Django 导入错误 : cannot import name 'x' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41320392/

相关文章:

python - Flask 应用程序退出时如何停止 Gunicorn

Python 日志记录和 Pydev 调试器?

python - kivy:为什么我不能改变矩形的颜色?

python - 更新 Django 中的字段不起作用

django - 模型的表单实例给出 id=None Django

python - 在 Django 中,如何从单个表单字段填充通用关系?

python - 用于代理实时站点的本地开发的 Django 存储后端?

python - NoReverseMatch 位于/accounts/detail

python - 如何使用 Django ORM 通过相关对象查询模型并获取查询集中的相关对象

python - django rest framework 过滤器忽略映射到枚举的 int 字段