Django测验app:属性错误

时间:2016-04-16 12:53:36

标签: python django

尝试进行测验时发生错误。虽然我的页面的属性错误与in this topic相同,但解决方案还没有解决我的问题。

我已经尝试过上述主题中提到的解决方案,但它没有解决我的问题。我把Django Quiz中的所有应用程序混合在一起,将模型放在同一个文件中,依此类推。目前它已正常运行,我已经能够毫无问题地管理“管理员”页面中的设置。

问题依赖于参加测验时,我收到了这个追溯:

Internal Server Error: /myquiz/take/
Traceback (most recent call last):
  File "C:\P4\myapp\models.py", line 359, in user_sitting
    sitting = self.get(user=user, quiz=quiz, complete=False)
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\models\manager.py", line 122, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\models\query.py", line 387, in get
    self.model._meta.object_name
myapp.models.DoesNotExist: Sitting matching query does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\handlers\base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\handlers\base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\views\generic\base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\P4\myapp\views.py", line 163, in dispatch
    self.quiz)
  File "C:\P4\myapp\models.py", line 361, in user_sitting
    sitting = self.new_sitting(user, quiz)
  File "C:\P4\myapp\models.py", line 339, in new_sitting
    questions = ",".join(map(str, questions_set)) + ","
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\models\query.py", line 258, in __iter__
    self._fetch_all()
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\models\query.py", line 1074, in _fetch_all
    self._result_cache = list(self.iterator())
  File "C:\Python\lib\site-packages\model_utils\managers.py", line 80, in iterator
    sub_obj = self._get_sub_obj_recurse(obj, s)
  File "C:\Python\lib\site-packages\model_utils\managers.py", line 153, in _get_sub_obj_recurse
    node = getattr(obj, rel)
AttributeError: 'int' object has no attribute 'essay_question'

似乎问题可能出现在essay_question模型或Sitting模型中。但是,我找不到这个问题的答案。这里有一些我认为与错误相关的代码,但是如果需要更多代码,请问(大多数部分与Django的测验应用程序保持一致)。

坐席经理模型

class SittingManager(models.Manager):

    def new_sitting(self, user, quiz):
        if quiz.random_order is True:
            questions_set = quiz.questions_set.all() \
                                            .select_subclasses() \
                                            .order_by('?')
        else:
            questions_set = quiz.questions_set.all() \
                                            .select_subclasses()

        questions_set = questions_set.values_list('id', flat=True)

        if questions_set.count() == 0:
            raise ImproperlyConfigured('Question set of the quiz is empty. '
                                       'Please configure questions properly')

        if quiz.max_questions and quiz.max_questions < questions_set.count():
            questions_set = questions_set[:quiz.max_questions]

        questions = ",".join(map(str, questions_set)) + ","

        new_sitting = self.create(user=user,
                                  quiz=quiz,
                                  question_order=questions,
                                  question_list=questions,
                                  incorrect_questions="",
                                  current_score=0,
                                  complete=False,
                                  user_answers='{}')
        return new_sitting

    def user_sitting(self, user, quiz):
        if quiz.single_attempt is True and self.filter(user=user,
                                                       quiz=quiz,
                                                       complete=True)\
                                               .exists():
            return False

        try:
            sitting = self.get(user=user, quiz=quiz, complete=False)
        except Sitting.DoesNotExist:
            sitting = self.new_sitting(user, quiz)
        except Sitting.MultipleObjectsReturned:
            sitting = self.filter(user=user, quiz=quiz, complete=False)[0]
        return sitting

QuizTake视图

EDITED

我很感激答案,因为它与此应用程序的其他类似错误的解决方案不同。我会提供更多所需信息,并感谢您的帮助。

编辑2:

我现在正试图进入'myquiz / take'视图:

Internal Server Error: /myquiz/take/
Traceback (most recent call last):
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\handlers\base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\handlers\base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\views\generic\base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\P4\myapp\views.py", line 171, in dispatch
    return super(QuizTake, self).dispatch(request, *args, **kwargs)
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\views\generic\base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\views\generic\edit.py", line 213, in get
    return self.render_to_response(self.get_context_data())
  File "C:\P4\myapp\views.py", line 206, in get_context_data
    context = super(QuizTake, self).get_context_data(**kwargs)
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\views\generic\edit.py", line 122, in get_context_data
    kwargs['form'] = self.get_form()
  File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\views\generic\edit.py", line 35, in get_form_with_form_class
    return get_form(self, form_class=form_class)
  File "C:\P4\myapp\views.py", line 184, in get_form
    return form_class(**self.get_form_kwargs())
TypeError: __init__() missing 1 required positional argument: 'question'

以下是我的views.py的摘录(似乎导致错误):

def dispatch(self, request, *args, **kwargs):
        self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name'])
        if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'):
            raise PermissionDenied

        self.logged_in_user = self.request.user.is_authenticated()

        if self.logged_in_user:
            self.sitting = Sitting.objects.user_sitting(request.user,
                                                        self.quiz)
        else:
            self.sitting = self.anon_load_sitting()

        if self.sitting is False:
            return render(request, 'single_complete.html')

        return super(QuizTake, self).dispatch(request, *args, **kwargs)

Get_form

def get_form(self, form_class):
        if self.logged_in_user:
            self.questions = self.sitting.get_first_questions()
            self.progress = self.sitting.progress()
        else:
            self.questions = self.anon_next_questions()
            self.progress = self.anon_sitting_progress()

        if self.questions.__class__ is Essay_Questions:
            form_class = EssayForm

        return form_class(**self.get_form_kwargs())

    def get_form_kwargs(self):
        kwargs = super(QuizTake, self).get_form_kwargs()

        return dict(kwargs, questions=self.questions)

FORM_VALID和get_context_data

def form_valid(self, form):
        if self.logged_in_user:
            self.form_valid_user(form)
            if self.sitting.get_first_questions() is False:
                return self.final_result_user()
        else:
            self.form_valid_anon(form)
            if not self.request.session[self.quiz.anon_q_list()]:
                return self.final_result_anon()

        self.request.POST = {}

        return super(QuizTake, self).get(self, self.request)

    def get_context_data(self, **kwargs):
        context = super(QuizTake, self).get_context_data(**kwargs)
        context['question'] = self.questions
        context['quiz'] = self.quiz
        if hasattr(self, 'previous'):
            context['previous'] = self.previous
        if hasattr(self, 'progress'):
            context['progress'] = self.progress
        return context

1 个答案:

答案 0 :(得分:1)

  

myapp.models.DoesNotExist:坐不匹配的查询不存在。

这正是它所说的。你正在尝试获取一个不存在的Sitting对象。因此,您需要使用try except来连接第359行,以便干净地处理这种情况。实际上,您可以按如下方式简化整个方法。

def user_sitting(self, user, quiz):
    if quiz.single_attempt is True and self.filter(user=user,
                                                   quiz=quiz,
                                                   complete=True)\
                                           .exists():
        return False

    try:
        return self.filter(user=user,quiz=quiz,complete=True)[0]
    except IndexError:
        return sitting = self.new_sitting(user, quiz)

更简单的代码更易于维护,您可以减少查询数量,从而提高性能。

  

AttributeError:&#39; int&#39;对象没有属性&#39; essay_question&#39;

这意味着您认为自己拥有Questions个实例,但实际拥有的是meta。堆栈跟踪的其余部分为您提供导致此错误的执行行。看一下提到你自己的代码的行,有些就在附近你调用一个方法,它应该返回一个Questions实例但是返回int。

它曾经工作并且不再起作用的原因是所谓的回归错误。某些代码段的更改使另一部分行为异常。最受欢迎,最可持续的解决方法是单元测试。