2011-12-28 24 views
2

另一个新手问题,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+"/") 

原来这里是视图的休息和模型

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': '',      
    } 
} 
+0

这里没有必要对交易做任何事情。你的原始代码是什么? – 2011-12-28 19:43:21

+0

尝试旧方法时会出现什么错误,以及新方法? – 2011-12-28 19:43:44

+0

在调试模式下,当我到达返回行时,page.id为None。旧方法和新方法之间没有区别,因为page.id都不是。 – cirik 2011-12-28 20:12:20

回答

4

删除t他从您的模型类id字段。

如果您没有指定主键,Django会自动插入名为id的自动字段,因此您不需要它。

因为你已经明确说过你的id字段是一个整数主键,Django希望你自己管理它。这是一个IntField,因为你声明,而不是AutoField,所以它不会自动分配任何值。

+0

谢谢,我会尝试但有另一个问题。如果我删除了id字段,我如何使用blogpost对象的主键重定向? – cirik 2011-12-28 21:10:30

+0

运行良好,只是从模型中删除了ID。 – cirik 2011-12-28 21:57:34

+2

如果你的模型定义中没有包含主键字段,Django会添加一个。它将被称为'id',并且将是一个自动递增整数字段。 – 2011-12-28 22:46:50

0

使用这个,而不是手动调用save()

页= BlogPost.objects.create(标题= PAGE_NAME,身体=内容, author = request.user,category = postCategory)

+0

创建也没有工作。与save()相同,它会添加到数据库中,但不会立即生效。 – cirik 2011-12-28 20:52:18

相关问题