Django自定义保存装饰器导致formset保存内部错误(内联在admin中)

时间:2013-02-08 19:45:52

标签: python django

我有一个自定义保存方法和一个自定义装饰器,用于在我的自定义保存之前和之后运行Django的模型save():

models.py:

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

def save_decorator(method_to_decorate):
    def wrapper(self, *args, **kwargs):
        super(type(self), self).save(*args, **kwargs)
        method_to_decorate(self, *args, **kwargs)
        super(type(self), self).save(*args, ** kwargs)
    return wrapper



class The_Image_Abstract(models.Model):

    class Meta:
        abstract = True

    create_time = models.DateTimeField(editable=False)


class Avatar(The_Image_Abstract):
    #I'm using this to track Avatar class in the template. There should be a better way.

    user = models.OneToOneField(User, related_name='avatar')

    @save_decorator
    def save(self, *args, **kwargs):
        "my stuff here"
        pass

在管理页面中保存或修改头像时,此功能非常有效。但是当Avatar在另一个模型的内联中保存为formset时会引发内部错误(formset在添加装饰器之前工作)。 这里出了什么问题?我看到有关人们在使用Postgres时收到此错误的帖子,我也使用Postgres,但我不认为这种情况是由Postgres引起的。

Request Method:     POST
Request URL:     http://localhost/admin/auth/normal_user/add/
Django Version:     1.4.3
Exception Type:     InternalError
Exception Value:     

current transaction is aborted, commands ignored until end of transaction block

Exception Location:     /home/eras/projects/kart/venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py in execute_sql, line 912
Python Executable:     /home/eras/projects/kart/venv/bin/python
Python Version:     2.7.3

任何帮助表示赞赏!

谢谢,

今朝

1 个答案:

答案 0 :(得分:0)

好的,我发现了这种情况发生的原因。它与装饰器有关,试图在设置一些没有默认值的非空字段之前保存模型。我不确定为什么只有在Admin inlines(formset)中保存新对象时才会导致错误。但是在运行自定义保存功能之前将这些必填字段设置为某个值可以解决问题。

相关问题