python - django - 不立即保存到数据库

标签 python django

另一个新手问题,

在我将项目保存到数据库后,我立即尝试访问 它的主键重定向其页面。但我无法完成它。 我尝试按照此 document 中的说明手动处理交易.

会不会是因为使用了管理员模式?

我收到这个错误:

 invalid literal for int() with base 10: 'None'

我将返回行更改为将 id 转换为字符串

 return HttpResponseRedirect("/blog/page/"+str(page.id)+"/")

这是代码段。

@transaction.commit_manually
def new_post_save(request):
    .
    .
    .
    page.save()  
    sid = transaction.savepoint()
    transaction.savepoint_commit(sid)
    return HttpResponseRedirect("/blog/page/"+page.id+"/")

这是原始 View 和模型的其余部分

def new_post_save(request):
page_name =  request.POST["page_name"]
content =  request.POST["content"]
postCategory = request.POST["cat"]

page = BlogPost(title = page_name,body = content, author = request.user, category = postCategory)

page.save()  
return HttpResponseRedirect("/blog/page/"+page.id+"/")

模型

class BlogPost(models.Model):
id = models.IntegerField(primary_key=True)
author = models.ForeignKey(User)
title = models.CharField(max_length=128)
body = models.TextField()
category = models.CharField(max_length=10, default='other')

def __unicode__(self):
    return self.title

这里是 base.py 我想我没有覆盖保存功能。

def save(self, force_insert=False, force_update=False, using=None):
    """
    Saves the current instance. Override this in a subclass if you want to
    control the saving process.

    The 'force_insert' and 'force_update' parameters can be used to insist
    that the "save" must be an SQL insert or update (or equivalent for
    non-SQL backends), respectively. Normally, they should not be set.
    """
    if force_insert and force_update:
        raise ValueError("Cannot force both insert and updating in model saving.")
    self.save_base(using=using, force_insert=force_insert, force_update=force_update)

    save.alters_data = True

在数据库的settings.py中

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', 
        'NAME': 'blog.db',                      
        'USER': '',                     
        'PASSWORD': '',                 
        'HOST': '',                    
        'PORT': '',                    
    }
}

最佳答案

从模型类中删除 id 字段。

如果你没有指定主键,Django 会自动插入一个名为 id 的 AutoField,所以你不需要它。

因为您已经明确表示您的 id 字段是一个整型主键,Django 希望您自己管理它。正如您声明的那样,它是一个 IntField,而不是一个 AutoField,因此它不会自动分配任何值。

关于python - django - 不立即保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8660472/

相关文章:

python - python 中的 sql INSERT(postgres、游标、执行)

python - 如何在 Python 中运行不可见的子进程?

python - 创建 Stripe 订阅 Python

python - 复制模型实例并更新字段

python - 从 Python 到 Mathematica 再返回

python - 我可以在 Python 中为继承的方法创建别名吗?

python - 使用 Django 和 Reportlab 从 HTML 生成 PDF

django - 在哪里存储 Django 应用程序的媒体文件以便在 docker 容器更新后保存它们?

python - Django 模板测试覆盖率

python - Django 2.2 无法连接到 AWS ElasticBeanstalk 上的 ElastiCache Redis