Admin中的Django模型pre_save验证 [英] Django model pre_save Validation in Admin

查看:199
本文介绍了Admin中的Django模型pre_save验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的模型:

class Product(models.Model):
    product_title = models.CharField(max_length=100, null=False, 
verbose_name='Product title')
    product_description = models.TextField(max_length=250, 
verbose_name='Product description')
    product_qty = models.IntegerField(verbose_name='Quantity')
    product_mrp = models.FloatField(verbose_name='Maximum retail price')
    product_offer_price = models.FloatField(verbose_name='Selling price')

def validate_produce_offer_price(sender, instance, **kwargs):
    if instance.product_offer_price > instance.product_mrp:
        from django.core.exceptions import ValidationError
        raise ValidationError('Product offer price cannot be greater than 
Product MRP.')


pre_save.connect(validate_produce_offer_price, sender=Product)

我正在尝试验证 product_offer_price ,然后保存模型。验证错误已成功引发,但在调试器创建的异常页面上。像管理员表单引发的其他错误一样,如何在管理员本身中显示表单错误?

I am trying to validate the product_offer_price before the model is saved. The Validation error is being raised successfully, but the on an exception page created by the debugger. How to show the error on the form in the admin itself like other errors raised by the admin form?

推荐答案

models.py



models.py

from django.db import models

class Product(models.Model):
    product_title = models.CharField(max_length=100, null=False, 
verbose_name='Product title')
    product_description = models.TextField(max_length=250, 
verbose_name='Product description')
    product_qty = models.IntegerField(verbose_name='Quantity')
    product_mrp = models.FloatField(verbose_name='Maximum retail price')
    product_offer_price = models.FloatField(verbose_name='Selling price')



forms.py



forms.py

from models import Product
from django import forms

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        exclude = [id, ]

    def clean(self):
        product_offer_price = self.cleaned_data.get('product_offer_price')
        product_mrp = self.cleaned_data.get('product_mrp')
        if product_offer_price > product_mrp:
            raise forms.ValidationError("Product offer price cannot be greater than Product MRP.")
        return self.cleaned_data



admin.py



admin.py

from django.contrib import admin
from forms import ProductForm
from models import Product

class ProductAdmin(admin.ModelAdmin):
    form = ProductForm
    list_display = ('product_title', 'product_description', 'product_qty', 'product_mrp', 'product_offer_price')

admin.site.register(Product, ProductAdmin)

这篇关于Admin中的Django模型pre_save验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆