【问题标题】:invalid literal for int() with base 10: with Django基数为 10 的 int() 的无效文字:使用 Django
【发布时间】:2020-02-24 08:34:46
【问题描述】:

我的模型: 我在 Django 中得到以 10 为底的 int() 的无效文字,它在 shell 中完美运行

class Category(models.Model):
    cat_id = models.IntegerField(primary_key=True)
    category_name = models.CharField(max_length=1000)
    created_at = models.DateField(auto_now=True ,max_length=30)
    def __str__(self):
        return self.category_name


class Content(models.Model):
    content_id = models.AutoField(primary_key=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    content = models.CharField(max_length=5000)
    created_at = models.DateField(auto_now=True)

    def __str__(self):
        return self.content

** 我的看法 **

def create_blog(request):
    if request.method == 'POST':
        title = request.POST['title']
        content = request.POST['content']
        category = request.POST['category']

        object_of_category = Category.objects.get(cat_id = (category))

        save_post = Content(category = object_of_category, content =content)

        save_post.save()
        return redirect(create_blog,{'message':'Post created Successfully!'})
    categories = Category.objects.all()
    return render(request ,'admin/create_blog.html', {'categories' : categories})

【问题讨论】:

  • 你能显示完整的异常跟踪日志吗?
  • @Abhijeet 您以错误的方式创建了模型。 Django 自动处理主键 ID
  • 模型中不需要添加cat_id、content_id字段。 Django 会自动为您完成。

标签: django django-models django-views


【解决方案1】:

我阅读了您的代码,并在您的代码中看到了这一点:

category = request.POST['category']

你应该注意你发布的内容 应该是int类型

因为在您的类别模型中:

cat_id = models.IntegerField(primary_key=True)

是整数类型

我认为您的所有代码都可以,但在此之前

object_of_category = Category.objects.get(cat_id = (category))

通过以下方式检查类别的类型:

type(category)

我的建议是使用 django.form 来防止这些 复杂性。

【讨论】:

    【解决方案2】:

    models.AutoField()不需要自己添加,是Django自动添加的,看这里https://docs.djangoproject.com/en/3.0/topics/db/models/#automatic-primary-key-fields

    您必须删除两个表中的自定义 ID 并更改您的 get 查询

    来自

    object_of_category = Category.objects.get(cat_id = (category))
    

    object_of_category = Category.objects.get(id=category)
    

    【讨论】:

      【解决方案3】:

      首先,您尝试在以下 sn-p 中获取值类别(字符串类型)的 id(整数类型): object_of_category = Category.objects.get(cat_id = (category))

      此外,除非绝对必要,否则避免创建主键字段,因为 Django 会自动为您创建。

      此外,Try.. Except 块在这种情况下非常有用,因为它们会生成 StackTraces 来显示您的错误源自何处。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-04
        • 2023-03-09
        • 1970-01-01
        • 2011-07-17
        相关资源
        最近更新 更多