如何修复创建Django模型管理器时发生的错误?

时间:2019-01-11 14:53:36

标签: python django django-models

我正在用django 2的antonio mele为例创建一个博客应用程序。 我的主题是创建模型管理器。 但是,一旦我编辑了models.py文件,承载本地服务器的Power Shell窗口就会显示此错误

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03B61300>
    Traceback (most recent call last):
      File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
        fn(*args, **kwargs)
      File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inne
    r_run
        autoreload.raise_last_exception()
      File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception
        raise _exception[1]
      File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\__init__.py", line 337, in execute
        autoreload.check_errors(django.setup)()
      File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
        fn(*args, **kwargs)
      File "C:\Users\public\django\my_env\lib\site-packages\django\__init__.py", line 24, in setup
        apps.populate(settings.INSTALLED_APPS)
      File "C:\Users\public\django\my_env\lib\site-packages\django\apps\registry.py", line 112, in populate
        app_config.import_models()
      File "C:\Users\public\django\my_env\lib\site-packages\django\apps\config.py", line 198, in import_models
        self.models_module = import_module(models_module_name)
      File "C:\Users\public\django\my_env\lib\importlib\__init__.py", line 127, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
      File "<frozen importlib._bootstrap>", line 983, in _find_and_load
      File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 728, in exec_module
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "C:\Users\public\django\mysite\blog\models.py", line 1, in <module>
        class PublishedManager(models.Manager):
    NameError: name 'models' is not defined

这是 models.py 文件

上的代码
class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager,
                    self).get_queryset()\
                        .filter(status='published')

class Post(models.Model):
                # ...
    objects = models.Manager() # The default manager.
    published = PublishedManager() # Our custom manager

@TDK无法确定“包含”的含义,但这是admin.py文件

from django.contrib import admin
from .models import Post

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug', 'author', 'publish',
                    'status')
list_filter = ('status', 'created', 'publish', 'author')
search_fields = ('title', 'body')
prepopulated_fields = {'slug': ('title',)}
raw_id_fields = ('author',)
date_hierarchy = 'publish'
ordering = ('status', 'publish')

@ Tony和Jonah,我添加了django.db导入模型中的代码  而且我也收到此错误消息

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x030233D8>
Traceback (most recent call last):
  File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inne
r_run
    self.check(display_num_errors=True)
  File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\base.py", line 425, in check
    raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:

ERRORS:
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'title', which is not a callable,
an attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'slug', which is not a callable, a
n attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'author', which is not a callable,
 an attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'publish', which is not a callable
, an attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'status', which is not a callable,
 an attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.

System check identified 5 issues (0 silenced).

我真的分享了错误的models.py文件。

@ Daniel文件中的完整代码:

from django.db import models

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager,
                    self).get_queryset()\
                        .filter(status='published')

class Post(models.Model):
    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250,
                            unique_for_date='publish')
    author = models.ForeignKey(User,
                                on_delete=models.CASCADE,
                                related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,
                                choices=STATUS_CHOICES,
                                default='draft')        
class Meta:
    ordering = ('-publish',)    

def __str__(self):
    return self.title
                            # ...
    objects = models.Manager() # The default manager.
    published = PublishedManager() # Our custom manager

这是我现在收到的错误消息

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x036C1420>
Traceback (most recent call last):
  File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inne
r_run
    autoreload.raise_last_exception()
  File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception
    raise _exception[1]
  File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\__init__.py", line 337, in execute
    autoreload.check_errors(django.setup)()
  File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\public\django\my_env\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\public\django\my_env\lib\site-packages\django\apps\registry.py", line 112, in populate
    app_config.import_models()
  File "C:\Users\public\django\my_env\lib\site-packages\django\apps\config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\public\django\my_env\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\public\django\mysite\blog\models.py", line 9, in <module>
    class Post(models.Model):
  File "C:\Users\public\django\mysite\blog\models.py", line 17, in Post
    author = models.ForeignKey(User,
NameError: name 'User' is not defined

2 个答案:

答案 0 :(得分:0)

我猜您尚未导入models代码:

from django.db import models

答案 1 :(得分:0)

正如我在评论中提到的那样,您可能忘记了包含

from django.db import models

现在该错误消失了,看来您也需要

from django.contrib.auth.models import User