__init __()只需1个参数(给定7个)

 牛仔很忙不闲 发布于 2023-02-11 19:39

我的实现缺少这个错误

模型:

class Person(models.Model):
    last_name = models.CharField(max_length=256)
    first_name = models.CharField(max_length=256)

    class Meta:
        abstract = True

class Supplier(Person):

    def __init__(self):
        super(Supplier, self).__init__()

class Item(models.Model):
    name = models.CharField(max_length=256)
    supplier = models.ForeignKey(Supplier)
    ...

def __unicode__(self):
    return self.name

浏览次数:

def ItemNew(request):
    if request.method == "POST":
        post_item = ItemNewForm(request.POST)
        ...
    else:
        item_form = ItemNewForm()

        return render(request, "item_new.html", {
                'item_form' : item_form,
        })

形式:

class ItemNewForm(forms.ModelForm):
    class Meta:
        model = Item

HTML:

...
{% csrf_token %} <{{ item_form.name }} {{ item_form.supplier }}
...

回溯:

TypeError at /item/add
__init__() takes exactly 1 argument (7 given)
Request Method: GET
Request URL:    
Django Version: 1.5.4
Exception Type: TypeError
Exception Value:    
__init__() takes exactly 1 argument (7 given)
Exception Location: C:\Python27\lib\site-packages\django\db\models\query.py in iterator, line 327
Python Executable:  C:\Python27\python.exe
Python Version: 2.7.5
Python Path:    
['E:\\projects\\WebPOS',
 'E:\\tools\\ide\\eclipse\\plugins\\org.python.pydev_3.0.0.201311051910\\pysrc',
 'E:\\projects\\WebPOS',
 'C:\\Python27\\lib\\site-packages\\distribute-0.6.49-py2.7.egg',
 'C:\\Python27\\DLLs',
 'C:\\Python27\\lib',
 'C:\\Python27\\lib\\lib-tk',
 'C:\\Python27',
 'C:\\Python27\\lib\\site-packages',
 'C:\\Python27\\lib\\site-packages\\setuptools-0.6c11-py2.7.egg-info',
 'C:\\WINDOWS\\SYSTEM32\\python27.zip',
 'C:\\Python27\\lib\\plat-win']
Server time:    Tue, 10 Dec 2013 07:45:07 +0800


Error during template rendering:

In template E:\projects\WebPOS\base\templates\item_new.html, error at line 14
__init__() takes exactly 1 argument (7 given)

4   
5   {% block sidebar %}
6   {% include "nav.html" %}
7   {% endblock %}
8   
9   {% block content %}
10  

Add New Item

11
12 {% csrf_token %} 13
{{ item_form.name }}
14
{{ item_form.supplier }}
15
16
17 {% endblock %} 18

Andrea Di Pe.. 7

问题在于

class Supplier(Person):

    def __init__(self):
        super(Supplier, self).__init__()

看看django.db.models.Model源代码

class Model(six.with_metaclass(ModelBase)):
    _deferred = False

    def __init__(self, *args, **kwargs):

你的__init__函数只将实例本身作为参数,但是django可能传递更多的参数.这就是你需要使用的原因*args, **kwargs.

为了更好地理解*args,**kwargs你可以看看这个

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有