【问题标题】:Django get_object_or_404 is not defined [closed]Django get_object_or_404 未定义[关闭]
【发布时间】:2017-01-08 10:50:14
【问题描述】:

我正在开发一个使用 django 的 ORM 的独立应用程序。在我的主应用程序中,我使用了 django 的 get_object_or_404 模块。

当我运行脚本时,我已经导入了它的所有依赖项,它给了我错误:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 438, in __protected_call__
    return self.run(*args, **kwargs)
  File "/root/standAlone/tasks.py", line 48, in task1
NameError: global name 'get_object_or_404' is not defined

这是我的完整脚本代码:

import django
from celery import Celery
from django.conf import settings
settings.configure(
    DATABASE_ENGINE    = "django.db.backends.mysql",
    DATABASE_NAME      = "database name",
    DATABASE_USER      = "username",
    DATABASE_PASSWORD  = "password",
    DATABASE_HOST      = "host",
    DATABASE_PORT      = "3306",
    INSTALLED_APPS     = ("myApp",)
)
django.setup()
from django.db import models
from myApp.models import *
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render,redirect
from django.shortcuts import get_list_or_404, get_object_or_404
from celery.decorators import task
from celery.utils.log import get_task_logger



app = Celery('tasks', broker='redis://broker_url')

@app.task(name="task1")
def task1(recipe_pk):
    recipe = get_object_or_404(Recipe, pk=recipe_pk) #error occurs here
    recipe.status = 'Completed'
    recipe.save()

有人知道如何解决这个问题吗?

【问题讨论】:

  • 这不是你的实际代码;错误发生在第 48 行,但少于您发布的代码中的错误。
  • 我的代码中有许多“任务”具有相同的测试功能。因为不想提问太长太乱,所以把多余的部分删掉了
  • 删除额外位的某处,您还删除了实际错误。您发布的代码不能有您描述的错误。
  • 我没有,我发问题的时候很小心,错误出现在我提到的那一行
  • 您的真实代码是否在单独的文件中?您绝对确定包含recipe = get_object_or_404(Recipe, pk=recipe_pk) 的文件也包含from django.shortcuts import get_list_or_404, get_object_or_404,并且导入发生在调用上方

标签: python django import


【解决方案1】:

尝试删除“django.shortcuts”的双重导入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-17
    • 2017-01-26
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    相关资源
    最近更新 更多