Django TypeError int() 参数必须是字符串或数字,而不是 'QueryDict'

Posted

技术标签:

【中文标题】Django TypeError int() 参数必须是字符串或数字,而不是 \'QueryDict\'【英文标题】:Django TypeError int() argument must be a string or a number, not 'QueryDict'Django TypeError int() 参数必须是字符串或数字,而不是 'QueryDict' 【发布时间】:2014-02-26 05:24:14 【问题描述】:

在我的索引页面上单击提交时出现 TypeError

int() argument must be a string or a number, not 'QueryDict'

我想传入用户和消息变量,这样当他们提交消息时,用户和消息都会保存在数据库中。目前,我没有看到在我的 index.html 中我应该如何使用传入的那些变量(用户和消息)来传递回该信息。

追溯

    Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/

Django Version: 1.6.1
Python Version: 2.7.2
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'SimpleMessage')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Josh\Documents\Message\SimpleMessage\SimpleMessage\views.py" in index
  56.       u.save()
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save
  545.                        force_update=force_update, update_fields=update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save_base
  573.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in _save_table
  635.                                       forced_update)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in _do_update
  665.         filtered = base_qs.filter(pk=pk_val)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
  590.         return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
  608.             clone.query.add_q(Q(*args, **kwargs))
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
  1198.         clause = self._add_q(where_part, used_aliases)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in _add_q
  1232.                     current_negated=current_negated)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_filter
  1125.         clause.add(constraint, AND)
File "C:\Python27\lib\site-packages\django\utils\tree.py" in add
  104.         data = self._prepare_data(data)
File "C:\Python27\lib\site-packages\django\db\models\sql\where.py" in _prepare_data
  79.             value = obj.prepare(lookup_type, value)
File "C:\Python27\lib\site-packages\django\db\models\sql\where.py" in prepare
  352.             return self.field.get_prep_lookup(lookup_type, value)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_lookup
  369.             return self.get_prep_value(value)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
  613.         return int(value)

Exception Type: TypeError at /
Exception Value: int() argument must be a string or a number, not 'QueryDict'

型号

class User (models.Model):
    name = models.CharField(max_length=20)

    def __unicode__(self):              
        return self.name

class Message (models.Model):
    content = models.TextField(max_length=140)
    user = models.ForeignKey(User)
    time = models.DateTimeField()

    def __unicode__(self):              
        return self.content

views.py

def index (request):
    if request.method == 'POST':
        u = User(request.POST)
        m = Message(request.POST)
        u.save()
        m.save()
        return render_to_response('index.html', 
                'user': u,
                'message': m,
                , RequestContext(request))
    else:
        u = User()
        m = Message()
        return render_to_response('index.html', 
                'user': u,
                'message': m,
                , RequestContext(request))

index.html

<form action="% url 'index' %" method = "post">
% csrf_token %
<input type="text" name="user" id="user" maxlength="20" placeholder = "Username">
<br>
<br>
<textarea rows="4" cols="35" name="text" maxlength="140" placeholder = "Message goes here"></textarea><br>
<input type="submit" value="Submit">
</form>

【问题讨论】:

什么是完整的回溯?确保获得文本版本(Django 错误页面中有一个链接)。 【参考方案1】:

您直接将POST 查询字典传递给模型的指令。

改变它:

u = User(request.POST)

收件人:

u = User(name=request.POST.get('user'))

还有,这个:

m = Message(request.POST)

收件人:

m = Message(content=request.POST.get('text'), user=u)

另外,如果您想自动添加消息时间,请更改此行:

time = models.DateTimeField()

收件人:

time = models.DateTimeField(auto_now_add=True)

【讨论】:

嗯,好的,所以 HTML id 将对应于模型,明白了。现在我在 m.save() 上收到一个 IntegrityError。 "异常值:SimpleMessage_message.content 不能为 NULL" 这里非常重要的一点是,您应该始终验证客户端数据,如果数据有效且干净,则将其传递或使用到您的模型。看看 Django Form 功能。

以上是关于Django TypeError int() 参数必须是字符串或数字,而不是 'QueryDict'的主要内容,如果未能解决你的问题,请参考以下文章

TypeError: int() 参数必须是字符串、类似字节的对象或实数,而不是“NoneType”

TypeError:无法在 Django 视图函数中解压不可迭代的 int 对象

TypeError:无法在 Django REST 框架中解压不可迭代的 int 对象

TypeError:entry() 缺少 1 个必需的位置参数:'title'(Django 帮助)

Django异常中间件:TypeError:object()不带参数

/writeReview/1 __str__ 处的 Django 模型 TypeError 返回非字符串(int 类型)