首页 文章

Django提出了ValueError:在POST上使用基数为10的int()的无效文字

提问于
浏览
0

Django一直在向服务器发送每个POST请求的 ValueError . 从巡航形式和SE,似乎这是我的Django模型的问题 . 但是,我不确定为什么模型会抛出这个错误或为什么Django会调用它们,因为它会在POST事件中抛出 .

查看问题:

def channel(request, channel):
    user_form = weblog_userForm(request.POST or None)
    if request.method == 'POST' and user_form.is_valid():
        nickname = user_form.cleaned_data['nickname']
        message = user_form.cleaned_data['message']
        password = user_form.cleaned_data['password']
        postDetails = {}

        ... process request and eventually ...

        return HttpResponse(json.dumps(postDetails), content_type="application/json")

我的应用模型:

class Line(models.Model):
    message = models.TextField(blank=True, default="")
    nick = models.CharField(max_length=50)
    hostname = models.CharField(max_length=300)
    channel = models.CharField(max_length=200)
    timestamp = models.DateTimeField(auto_now_add=True)
    LINE_TYPES = (
        ('PMSG', 'PRIVMSG'),
        ('SMSG', 'SOCKETMSG'),
        ('WMSG', 'WEBMSG'),
        ('NTCE', 'NOTICE'),
        ('ACTN', 'ACTION'),
        ('JOIN', 'JOIN'),
        ('PART', 'PART'),
        ('QUIT', 'QUIT'),
        ('NICK', 'NICK'),
        ('TPIC', 'TOPIC'),
    )
    msgType = models.CharField(max_length=4, choices=LINE_TYPES, default='PRIVMSG')

    def __str__(self):
        return self.message

class banned_ips(models.Model):
    bannedIp = models.GenericIPAddressField()

追溯:

Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/django/weblogs/log/views.py", line 96, in channel
    json_data = serializers.serialize("json", list(reversed(Line.objects.filter(id__gt=latest_line_id, channel=channel).order_by('-id')[:100])))
File "/usr/local/lib/python3.5/dist-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 836, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 854, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/query.py", line 1252, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/query.py", line 1276, in _add_q
    split_subq=split_subq,
File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/query.py", line 1214, in build_filter
    condition = self.build_lookup(lookups, col, value)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/query.py", line 1084, in build_lookup
    lookup = lookup_class(lhs, rhs)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/lookups.py", line 18, in __init__
    self.rhs = self.get_prep_lookup()
File "/usr/local/lib/python3.5/dist-packages/django/db/models/lookups.py", line 68, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/__init__.py", line 947, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: ''

任何帮助或想法将不胜感激,真的在这个问题上摸不着头脑 .

1 回答

  • 1

    guillermo chamorro和口袋国王都在这里找到了我的捕获 . 在我的 views.py snip中发布的(看似无关的)逻辑块中,是以下代码:

    if (request.is_ajax()):
        latest_line_id = request.GET.get('latest_id', '')
        if latest_line_id == '-1': # Return all lines
            json_data = serializers.serialize("json", list(reversed(Line.objects.filter(channel=channel).order_by('-id')[:100])))
        else:
            json_data = serializers.serialize("json", list(reversed(Line.objects.filter(id__gt=latest_line_id, channel=channel).order_by('-id')[:100])))
        return HttpResponse(json_data, content_type="application/json")
    

    尽管逻辑上从未被调用过,但两个回复者都是正确的,因为Django仍试图评估 json_data .

    如果 latest_line_id 为空(因为它将在POST请求中),它将被设置为 '' ,这将在尝试基于此id的数据库查询时由Django触发 ValueError . 这可以通过尝试在Django shell中自己查询过滤器来证明(使用 $python manage.py shell ):

    (注意:如果使用django shell,请不要忘记使用 from <yourapp>.models import <yourModel> 之类的东西导入模型)

    >>> list(Line.objects.filter(channel="test").filter(id__lte='').order_by('id'))
    Traceback (most recent call last):
    ...
    ValueError: invalid literal for int() with base 10: ''
    

    经验教训,在编辑视图时要非常勤奋并记得仔细检查所有逻辑块并在阅读追溯时要小心(额外的一双眼睛可以帮助 ;) ) . 希望我的疏忽可以在我失去的时候拯救别人 .

相关问题