从models.py在django Web应用程序中引发用户定义的异常

时间:2014-03-05 18:02:43

标签: python django django-models

这是我的models.py文件

class DiskDrive(models.Model):
    deviceId = models.CharField(max_length=64, primary_key=True)
    freeSpace = models.BigIntegerField()

    def __str__(self):
        return self.deviceId


class StoragePool(models.Model):
    poolId = models.CharField(max_length=256, primary_key=True)
    size = models.BigIntegerField()
    freeSpace = models.BigIntegerField()
    drive = models.ForeignKey(DiskDrive, related_name='pools')

    def __str__(self):
        return self.poolId

class DriveFull(Exception):
    STD_MESSAGE = 'Not enough free space in the selected Drive'
    def __init__(self):
        self.msg = DriveFull.STD_MESSAGE
        self.resp()

    def resp(self):
        request = HttpRequest()
        return render(request,'sim/error_detail.html',
                     {'drive_name' : "a",
                      'error_message' : "The selected drive doesn't have desired free space to create the Storage Pool.",})
    #def __str__(self):
         #   return self.msg

@receiver(pre_save,sender=StoragePool)
def check_drive_space(sender, instance, **kwargs):
    if(instance.drive.freeSpace<instance.size):
        raise DriveFull
        #render_to_response("sim/error_detail.html", {"error_message": "The selected drive doesn't have desired free space to create the Storage Pool."})
........

我的admin.py

....
admin.site.register(DiskDrive)
admin.site.register(StoragePool)

&安培;因此Django提供默认的网页来做操作。

现在,当有人试图在没有足够空间的驱动器中创建存储池时,我想在Django中引发用户定义的异常。 我从stackoverflow.com =&gt; Django: User-defined exception not being caught

开始关注此链接

我创建了DriveFull(Exception)类&amp;试图这样做,但它在浏览器上显示了Django的黄色堆栈跟踪页面。显示该页面中的错误消息。 但我想在我创建的.html页面上呈现此消息。 有人可以告诉我该怎么做? 提前致谢。      我在浏览器上获得了以下Traceback:

DriveFull at /admin/sim/storagepool/add/
No exception message supplied
Request Method: POST
Request URL:    http://localhost:8000/admin/sim/storagepool/add/
Django Version: 1.7
Exception Type: DriveFull
Exception Location: F:\Project Python\My_Project\storagesim\sim\models.py in check_drive_space,      line 54
Python Executable:  C:\Python33\python.exe
Python Version: 3.3.2

0 个答案:

没有答案