flask admin ImportError

时间:2014-08-17 13:12:43

标签: model flask flask-admin

我创建了两个名为' Topics'和' SubTopics'。我的SubTopic模型类导入Topic类,因为没有主题就无法创建子主题。这一切都很有效,直到我尝试添加删除主题的功能。

在删除主题之前,我必须检查所选主题是否包含任何子主题,以及是否确实避免用户删除该主题。所以为了实现这一点,我必须导入“SubTopic”#39;课堂内部'主题'检查用户尝试删除的主题是否存在子主题。

这导致应用程序崩溃,因为' SubTopic'已经导入了主题'所以通过导入SubTopic'内部'主题'创建了ImportError。

如何解决此问题?为了便于阅读和清洁,我喜欢将每个模型保存在不同的类中。

这是我的目录列表

/
model/
  Topic.py
  SubTopic.py
run.py

请在下面找到代码,

Topic.py

import datetime
import uuid
import os

# from model.Questions import Questions  ---- > ImportError
# from model.SubTopics import SubTopics  -----> ImportError
from app import db
from flask.ext.admin.contrib.mongoengine import ModelView
from flask.ext.login import current_user
from Users import User
from flask import request, flash
from constants import *
from wtforms.fields import FileField
from flask.ext.admin.model.template import macro
from wtforms.validators import ValidationError


class Topics(db.Document):
    topicName = db.StringField(required=True)
    haveSubtopics = db.BooleanField()
    image = db.StringField()
    createdBy = db.ReferenceField(User)
    updatedBy = db.ReferenceField(User)
    createdDate = db.DateTimeField(default=datetime.datetime.now())

    def get_all_topics(self):
        topicList = Topics.objects.all()

        if(topicList):
            return topicList
        else:
            return None

    def get_topic(self, id):
        topic = Topics.objects.get(pk=id)

        if(topic):
            return topic
        else:
            return None


    def __unicode__(self):
        return self.topicName

    def delete(self):
        dataCnt = 0
        if self.haveSubtopics:
            dataCnt = SubTopics.objects(mainTopic=self.pk).count()  ---> Check sub topic exits before delete
        else:
            dataCnt = Questions.objects(topic=self.pk).count()  ----> Check questions exits before delete

        if dataCnt > 0:
            flash('Cannot delete this topic. Questions or sub topic exists under this topic')
            return False
        else:
            if not self.image is None:
                if os.path.isfile(self.image):
                 os.unlink(self.image)

            self.delete()
            return True

class TopicsView(ModelView):
    def is_accessible(self):
        if current_user.is_authenticated():
            return True
        else:
           return False

    column_list = ('topicName','createdDate','haveSubtopics')
    column_labels = dict(topicName='Topic', createdDate='Created Date', haveSubtopics='Sub Topics')

    form_excluded_columns = ('createdBy','createdDate', 'updatedBy')

    create_template = 'create_topic_form.html'
    edit_template = 'edit_topic_form.html'
    list_template = 'list_topics.html'

SubTopics.py

import datetime

from app import db
from model.Topics import Topics
from flask.ext.admin.contrib.mongoengine import ModelView
from flask.ext.login import current_user
from Users import User
from constants import *
from flask import request
from wtforms.validators import ValidationError
from flask.ext.admin.model.template import macro


class SubTopics(db.Document):
    subTopicName = db.StringField(required=True)
    mainTopic = db.ReferenceField(Topics, required=True)
    createdBy = db.ReferenceField(User, required=True)
    createdDate = db.DateTimeField(default=datetime.datetime.now())

    def get_all_subtopics(self, topicid):
        subTopicList = SubTopics.objects(mainTopic=topicid)

        if(subTopicList):
            return subTopicList
        else:
            return None

    def __unicode__(self):
        return self.subTopicName


class SubTopicsView(ModelView):
    def is_accessible(self):
        if current_user.is_authenticated():
            return True
        else 
           return False

    column_list = ('subTopicName','mainTopic', 'createdDate')
    column_labels = dict(subTopicName='Name', mainTopic='Topic', createdDate = 'Created Date')

    form_excluded_columns = ('createdBy','createdDate')

    def check_mainTopic(self, form):
        topi = request.form['mainTopic']
        topicObj = Topics.objects.with_id(topi)

        if topicObj:
            if not topicObj.haveSubtopics:
                raise ValidationError('Selected topic cannot have sub topics')

    form_args = dict(
        subTopicName=dict(label='Name'),
        mainTopic=dict(label='Topic', validators = [check_mainTopic])
    )

    list_template = 'list_sub_topics.html'

先谢谢了,

3 个答案:

答案 0 :(得分:1)

不导入子主题,或不导入主题。例如,要检查主题是否有任何子主题,应该足以检查子列表是否为空。 Python的duck typing意味着你不需要导入来访问对象的方法。如果您发布代码,我可以更具体。

答案 1 :(得分:0)

如果您要寻找代码的快速解决方案,可以在删除方法中导入QuestionSubTopic

def delete(self):
    import model
    dataCnt = 0
    if self.haveSubtopics:
        dataCnt = model.SubTopics.objects(mainTopic=self.pk).count()
    else:
        dataCnt = model.Questions.objects(topic=self.pk).count()

    if dataCnt > 0:
        flash('Cannot delete this topic. Questions or sub topic exists under this topic')
        return False
    else:
        if not self.image is None:
            if os.path.isfile(self.image):
             os.unlink(self.image)

        self.delete()
        return True

答案 2 :(得分:0)

只需在模型__init__.py

中添加folder即可