简体   繁体   English

django自定义模板标签-导入模型博客错误

[英]django custom template tag - import model blog error

I am trying to import a model class called BlogDetails to use in my customised template tags page. 我正在尝试导入一个名为BlogDetails的模型类,以在我的自定义模板标签页面中使用。

Here is the structure of my app: 这是我的应用程序的结构:

appname (directory)
  -->core (directory)
    -->models.py (file)
    -->templatetags (directory)
      -->customised_template_tags.py (file)

Here is the import statements in the customised_template_tags.py file. 这是customised_template_tags.py文件中的import语句。 This is the same structure of other import statements I have used in my view files: 这与我在视图文件中使用的其他导入语句的结构相同:

import datetime
import os

from django import template
from django.conf import settings
from django.templatetags.static import static
from django.utils.safestring import mark_safe
from django.utils.translation.trans_real import gettext

from appname.common.utils import get_supported_language_code
from appname.core.models import BlogDetails

register = template.Library()

Here is the import statement on the models.py file at line 76 (refered to in the error message) that imports code from the customised_template_tags.py file: 这是在第76行 (错误消息中models.py文件上的import语句,该语句从customised_template_tags.py文件中导入代码:

from appname.core.templatetags.customised_template_tags import absolute_static, alternative_file, \
    file_url

Here is the error message: 这是错误消息:

  File "C:\Users\me\desktop\appname\appname\core\models.py", line 76, in <module>
    from appname.core.templatetags.customised_template_tags import absolute_static, alternative_file, \
  File "C:\Users\me\desktop\appname\appname\core\templatetags\customised_template_tags.py", line 11, in <module>
    from appname.core.models import BlogDetails
ImportError: cannot import name 'BlogDetails'

I have re-started my development server and I have read this thread and followed the suggestions in the answer and I have also read the django docs . 我已经重新启动了开发服务器,并且已经阅读了该线程并遵循了答案中的建议,并且还阅读了django docs

Can anyone suggest the solution to my issue? 谁能建议我的问题的解决方案?

You do a circular import: 您进行循环导入:

  1. appname.core.models tries to import appname.core.templatetags.customised_template_tags appname.core.models尝试导入appname.core.templatetags.customised_template_tags
  2. appname.core.templatetags.customised_template_tags tries to import appname.core.models appname.core.templatetags.customised_template_tags尝试导入appname.core.models
  3. Because appname.core.models hasn't finished to load, it can't be imported, so it fails. 由于appname.core.models尚未完成加载,因此无法导入,因此失败。

A quick fix: 快速修复:

Import your model inside your tag function. 将模型导入标签功能中。
Or the opposite, import your tag only in the function where you use it. 或相反,仅在使用标记的函数中导入标记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM