gpt4 book ai didi

管理中的 Django 模型 pre_save 验证

转载 作者:行者123 更新时间:2023-12-02 06:57:30 26 4
gpt4 key购买 nike

以下是我的模型:

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。验证错误已成功引发,但出现在调试器创建的异常页面上。如何在管理本身的表单上显示错误,就像管理表单引发的其他错误一样?

exception raised during changing the existing data Exception raised while adding new data

最佳答案

模型.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

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

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)

关于管理中的 Django 模型 pre_save 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46038262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com