Django引发ValueError:对于int()无效的字面量,POST上的基数为10

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: ''

任何帮助或想法,将不胜感激,真正抓住我的头。


吉列尔莫·查莫罗和口袋国王都在这里找到了我。 在我的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")

尽管逻辑上从来没有被调用过,但这两个响应者都是正确的, ValueError失败源于Django,然而却试图评估json_data

如果latest_line_id是空白的(就像在POST请求中那样),它将被设置为'' ,这将在尝试基于这个id的db查询时由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: ''

获得的经验教训,在编辑视图时要非常勤奋,并且记得仔细检查所有的逻辑块,并且在阅读回溯时多加小心(多一双眼睛可以提供帮助;) )。 希望我的失察能够帮助别人节省我输的时间。

链接地址: http://www.djcxy.com/p/86479.html

上一篇: Django raising ValueError: invalid literal for int() with base 10 on POST

下一篇: No module named 'polls.apps.PollsConfigdjango'; Django project tutorial 2