数据插入错误:以 10 为基数的 int() 的文字无效

发布于 2024-10-02 11:20:01 字数 4588 浏览 7 评论 0原文

我在 Google App Engine 上使用 Django-nonrel。我正在尝试向数据库添加一行,但在尝试使用 save() 时出现此错误:

以 10 为基数的 int() 的文字无效

这是我的代码:

views.py

from django import forms
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from forms import SayForm
from models import Saying, Category
import datetime

def say_something(request):
if request.method == 'POST':
    form = SayForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        content = cd['content']
        category_temp = "Uncategorized"
        category = Category.objects.get(name = category_temp)
        added_date = datetime.datetime.now()
        added_user = request.user
        saying = Saying(content, category, added_date, added_user)
        saying.save()
        return HttpResponseRedirect('/contribute/success')
else:
    form = SayForm()
return render_to_response('say_form.html', {'form' : form})

models.py

from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    name = models.CharField(max_length = 50)

    def __unicode__(self):
        return self.name

class Saying(models.Model):
    content = models.CharField(max_length = 160)
    category = models.ForeignKey(Category)
    added_date = models.DateField()
    added_user = models.ForeignKey(User)

forms.py

from django import forms

class SayForm(forms.Form):
    content = forms.CharField(widget = forms.Textarea)

    def clean_message(self):
        content = self.cleaned_data['content']
        num_characters = len(content)
        if num_characters > 160:
            raise forms.ValidationError("Please limit your saying to 160 characters only.")
        num_words = len(content.split())
        if num_words < 4:
            raise forms.ValidationError("This doesn't make sense. Say something longer.")
        return content

编辑:这是回溯

回溯:文件 “/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/core/handlers/base.py” 在获取响应中 107. 响应=回调(请求, *callback_args,**callback_kwargs)

文件 “/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/contrib/auth/decorators.py” 在 _wrapped_view 中 25. return view_func(request, *args, **kwargs)

文件 “/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/core/views.py” 在说_某事中 36. say.save()

文件 “/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/base.py” 在保存中 452. self.save_base(使用=使用, 强制插入=强制插入, force_update=force_update)

文件 “/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/base.py” 在保存库中 550. for f in meta.local_fields]

文件 “/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/subclassing.py” 在内部 28. return func(*args, **kwargs)

文件 “/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/subclassing.py” 在内部 28. return func(*args, **kwargs)

文件 “/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/init.py” 在 get_db_prep_save 中 280.返回self.get_db_prep_value(值, 连接=连接,准备=假)

文件 “/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/subclassing.py” 在内部 53. return func(*args, **kwargs)

文件 “/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/init.py” 在 get_db_prep_value 中 492.返回connection.ops.value_to_db_auto(value)

文件 “/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/djangotoolbox/db/base.py” 在 value_to_db_auto 中 68.返回超级(NonrelDatabaseOperations, self).value_to_db_auto(值)

文件 “/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/backends/init.py” 在 value_to_db_auto 中 485.返回int(值)

异常类型:ValueError at /contribute/ 异常值:无效 以 10 为基数的 int() 的文字:'test'

我的直觉告诉我,问题出在我如何将对象保存到数据库中。也许是外键部分?由于我最近才开始学习 Django,所以我无法确定问题所在。这个问题与使用GAE后端的Django-nonrel有什么关系吗?谁能告诉我我哪里错了?

I'm using Django-nonrel on Google App Engine. I'm trying to add a row to the database but I get this error when trying to use save():

invalid literal for int() with base 10

Here's my code:

views.py

from django import forms
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from forms import SayForm
from models import Saying, Category
import datetime

def say_something(request):
if request.method == 'POST':
    form = SayForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        content = cd['content']
        category_temp = "Uncategorized"
        category = Category.objects.get(name = category_temp)
        added_date = datetime.datetime.now()
        added_user = request.user
        saying = Saying(content, category, added_date, added_user)
        saying.save()
        return HttpResponseRedirect('/contribute/success')
else:
    form = SayForm()
return render_to_response('say_form.html', {'form' : form})

models.py

from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    name = models.CharField(max_length = 50)

    def __unicode__(self):
        return self.name

class Saying(models.Model):
    content = models.CharField(max_length = 160)
    category = models.ForeignKey(Category)
    added_date = models.DateField()
    added_user = models.ForeignKey(User)

forms.py

from django import forms

class SayForm(forms.Form):
    content = forms.CharField(widget = forms.Textarea)

    def clean_message(self):
        content = self.cleaned_data['content']
        num_characters = len(content)
        if num_characters > 160:
            raise forms.ValidationError("Please limit your saying to 160 characters only.")
        num_words = len(content.split())
        if num_words < 4:
            raise forms.ValidationError("This doesn't make sense. Say something longer.")
        return content

Edit: here's the backtrace

Traceback: File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/core/handlers/base.py"
in get_response
107. response = callback(request,
*callback_args, **callback_kwargs)

File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/contrib/auth/decorators.py"
in _wrapped_view
25. return view_func(request, *args, **kwargs)

File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/core/views.py"
in say_something
36. saying.save()

File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/base.py"
in save
452. self.save_base(using=using,
force_insert=force_insert,
force_update=force_update)

File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/base.py"
in save_base
550. for f in meta.local_fields]

File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/subclassing.py"
in inner
28. return func(*args, **kwargs)

File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/subclassing.py"
in inner
28. return func(*args, **kwargs)

File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/init.py"
in get_db_prep_save
280. return self.get_db_prep_value(value,
connection=connection, prepared=False)

File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/subclassing.py"
in inner
53. return func(*args, **kwargs)

File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/models/fields/init.py"
in get_db_prep_value
492. return connection.ops.value_to_db_auto(value)

File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/djangotoolbox/db/base.py"
in value_to_db_auto
68. return super(NonrelDatabaseOperations,
self).value_to_db_auto(value)

File
"/home/eeyorexd/workspace/Python/appengine/something-to-say/somethingtosay/django/db/backends/init.py"
in value_to_db_auto
485. return int(value)

Exception Type: ValueError at
/contribute/ Exception Value: invalid
literal for int() with base 10: 'test'

My gut feeling tells me that the problem lies somewhere around how I save the object to the database. Maybe the foreign key part? I can't pinpoint the problem since I just started learning Django recently. Does this problem have anything to do with Django-nonrel using GAE's backend? Can anyone tell me where I went wrong here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

锦欢 2024-10-09 11:20:01

问题就在这里:

saying = Saying(content, category, added_date, added_user)

您忘记了 Django 在模型定义中添加了一个自动 id 字段。如果您在 shell 中执行此操作,然后打印 saying.__dict__,您会看到内容已分配给 id,类别分配给 content >,等等。

相反,在实例化模型时始终使用关键字参数:

saying = Saying(content=content, 
                category=category, 
                added_date=added_date, 
                added_user=added_user)

The problem is here:

saying = Saying(content, category, added_date, added_user)

You've forgotten that Django adds an automatic id field to the model definition. If you did this in the shell, then printed saying.__dict__, you would see that the content has been assigned to id, the category to content, and so on.

Instead, always use keyword arguments when instantiating a model:

saying = Saying(content=content, 
                category=category, 
                added_date=added_date, 
                added_user=added_user)
晒暮凉 2024-10-09 11:20:01

创建这样的实例会将模型的主键设置为 content

saying = Saying(content, category, added_date, added_user)

这不会起作用,因为您的模型有一个数字主键,默认情况下所有模型都是如此,除非您明确告诉它使用其他字段作为主键。当 Django 尝试对值调用 int() 将其转换为整数时,它会因类型错误而崩溃。

您应该使用关键字参数,如下所示:

saying = Saying(content = content, ... = ...)

执行此操作的惯用方法,因为您无论如何都想保存对象:

saying = Saying.objects.create(content = content, ... = ..)

Creating an instance like this will set the primary key of your model to content:

saying = Saying(content, category, added_date, added_user)

Which won't work, because your model has a numeric primary key, as do all models by default unless you explicitly tell it to use some other field for the primary key. When Django tries to call int() on the value to cast it to integer, it crashes with a type error.

You should instead use keyword arguments, like this:

saying = Saying(content = content, ... = ...)

The idiomatic way to do this, as you want to save the object anyway:

saying = Saying.objects.create(content = content, ... = ..)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文