Django ForeignKey'对象没有属性'model'

时间:2017-03-08 11:36:06

标签: django django-models django-admin

我有两个模型(eisfiles和AuthPermissionAdd),我正在尝试添加一对多关系,如下面的代码所示。但由于某种原因,我得到“ForeignKey”对象没有属性'模型'。请帮助我在哪里做错了。

 class eisfiles(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    htmlname = models.CharField(max_length=100)
    meterId = models.CharField(max_length=100)
    esiid = models.CharField(max_length=100)
    metermultiplier = models.CharField(max_length=100)
    DbName = models.CharField(max_length=100,default='test')
    DbTable = models.CharField(max_length=100)
    address=models.CharField(max_length=100)

    def __str__(self):
        return self.htmlname
    def __str__(self):
        return self.DbName
    def __str__(self):
        return self.address

class AuthPermissionAdd(models.Model):
    user_id = models.CharField(max_length=500)
    eisfiles_id = models.ForeignKey(eisfiles)
    temp_id_id_id = models.IntegerField(blank=True, null=True)
    # print eisfiles_id


    Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inne
    autoreload.raise_last_exception()
  File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Python27\lib\site-packages\django\__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "C:\Python27\lib\site-packages\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Python27\Lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
  File "D:\python\project\energy_style\myapp\login\models.py", line 332, in <module>
    class AuthPermissionAdd(models.Model):
  File "D:\python\project\energy_style\myapp\login\models.py", line 338, in AuthPermissionAdd
    print eisfiles_id;
  File "C:\Python27\lib\site-packages\django\utils\six.py", line 842, in <lambda>
    klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 188, in __str__
    model = self.model
AttributeError: 'ForeignKey' object has no attribute 'model'

如果我从模型中删除print语句并尝试添加项目,则会显示以下错误

Environment:


Request Method: GET
Request URL: http://localhost:9090/admin/login/authpermissionadd/add/

Django Version: 1.9.4
Python Version: 2.7.11
Installed Applications:
['login',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rolepermissions']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template C:\Python27\lib\site-packages\django\contrib\admin\templates\admin\change_form.html, error at line 33
   __str__ returned non-string (type NoneType)   23 : {% endblock %}
   24 : {% endif %}
   25 : 
   26 : {% block content %}<div id="content-main">
   27 : {% block object-tools %}
   28 : {% if change %}{% if not is_popup %}
   29 :   <ul class="object-tools">
   30 :     {% block object-tools-items %}
   31 :     <li>
   32 :         {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %}
   33 :         <a href="{% add_preserved_filters histo ry_url %}" class= "historylink">{% trans "History" %}</a>
   34 :     </li>
   35 :     {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %}
   36 :     {% endblock %}
   37 :   </ul>
   38 : {% endif %}{% endif %}
   39 : {% endblock %}
   40 : <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %}
   41 : <div>
   42 : {% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1" />{% endif %}
   43 : {% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}" />{% endif %}


Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  174.                     response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  172.                     response = response.render()

File "C:\Python27\lib\site-packages\django\template\response.py" in render
  160.             self.content = self.rendered_content

File "C:\Python27\lib\site-packages\django\template\response.py" in rendered_content
  137.         content = template.render(context, self._request)

File "C:\Python27\lib\site-packages\django\template\backends\django.py" in render
  95.             return self.template.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  206.                     return self._render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in _render
  197.         return self.nodelist.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  992.                 bit = node.render_annotated(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render_annotated
  959.             return self.render(context)

File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  173.         return compiled_parent._render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in _render
  197.         return self.nodelist.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  992.                 bit = node.render_annotated(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render_annotated
  959.             return self.render(context)

File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  173.         return compiled_parent._render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in _render
  197.         return self.nodelist.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  992.                 bit = node.render_annotated(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render_annotated
  959.             return self.render(context)

File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  69.                 result = block.nodelist.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  992.                 bit = node.render_annotated(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render_annotated
  959.             return self.render(context)

File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  69.                 result = block.nodelist.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  992.                 bit = node.render_annotated(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render_annotated
  959.             return self.render(context)

File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render
  220.                     nodelist.append(node.render_annotated(context))

File "C:\Python27\lib\site-packages\django\template\base.py" in render_annotated
  959.             return self.render(context)

File "C:\Python27\lib\site-packages\django\template\loader_tags.py" in render
  209.                 return template.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  208.                 return self._render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in _render
  197.         return self.nodelist.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  992.                 bit = node.render_annotated(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render_annotated
  959.             return self.render(context)

File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render
  220.                     nodelist.append(node.render_annotated(context))

File "C:\Python27\lib\site-packages\django\template\base.py" in render_annotated
  959.             return self.render(context)

File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render
  220.                     nodelist.append(node.render_annotated(context))

File "C:\Python27\lib\site-packages\django\template\base.py" in render_annotated
  959.             return self.render(context)

File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render
  326.                 return nodelist.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  992.                 bit = node.render_annotated(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render_annotated
  959.             return self.render(context)

File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render
  326.                 return nodelist.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  992.                 bit = node.render_annotated(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render_annotated
  959.             return self.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  1049.         return render_value_in_context(output, context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render_value_in_context
  1026.     value = force_text(value)

File "C:\Python27\lib\site-packages\django\utils\encoding.py" in force_text
  78.                 s = six.text_type(s)

File "C:\Python27\lib\site-packages\django\utils\html.py" in <lambda>
  381.         klass.__unicode__ = lambda self: mark_safe(klass_unicode(self))

File "C:\Python27\lib\site-packages\django\forms\boundfield.py" in __str__
  43.         return self.as_widget()

File "C:\Python27\lib\site-packages\django\forms\boundfield.py" in as_widget
  101.         return force_text(widget.render(name, self.value(), attrs=attrs))

File "C:\Python27\lib\site-packages\django\contrib\admin\widgets.py" in render
  291.             'widget': self.widget.render(name, value, *args, **kwargs),

File "C:\Python27\lib\site-packages\django\forms\widgets.py" in render
  528.         options = self.render_options(choices, [value])

File "C:\Python27\lib\site-packages\django\forms\widgets.py" in render_options
  554.         for option_value, option_label in chain(self.choices, choices):

File "C:\Python27\lib\site-packages\django\forms\models.py" in __iter__
  1110.             yield self.choice(obj)

File "C:\Python27\lib\site-packages\django\forms\models.py" in choice
  1117.         return (self.field.prepare_value(obj), self.field.label_from_instance(obj))

File "C:\Python27\lib\site-packages\django\forms\models.py" in label_from_instance
  1180.         return smart_text(obj)

File "C:\Python27\lib\site-packages\django\utils\encoding.py" in smart_text
  42.     return force_text(s, encoding, strings_only, errors)

File "C:\Python27\lib\site-packages\django\utils\encoding.py" in force_text
  80.                 s = six.text_type(bytes(s), encoding, errors)

Exception Type: TypeError at /admin/login/authpermissionadd/add/
Exception Value: __str__ returned non-string (type NoneType)

1 个答案:

答案 0 :(得分:1)

看起来您的__str__方法正在返回None。由于__str__方法会返回CharField的结果,因此表明您的CharFields中包含None的值为空,这是不寻常的。

您可以修复数据库中的空值,也可以更改__str__方法,例如:

from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class eisfiles(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    ...

    def __str__(self):
        return unicode(self.address)  # use str() in Python 3

请注意,如果您使用的是Python 2并定义__str__而不是__unicode__,那么您应该使用python_2_unicode_compatible装饰器。

在您的问题中,您对同一模型有三种__str__方法。只使用最后一个,前两个将被忽略。