【问题标题】:Django model pre_save Validation in Admin管理员中的 Django 模型 pre_save 验证
【发布时间】:2018-02-12 18:19:04
【问题描述】:

以下是我的模型:

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

【问题讨论】:

  • 对答案做了很多改动,现在可以试试了

标签: django django-models django-admin


【解决方案1】:

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

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)

【讨论】:

  • ProductForm类Meta中是否需要添加“字段”?
  • @GautamMandewalker 已更新,您可以在那里使用字段/排除
  • django.core.exceptions.ImproperlyConfigured:禁止创建没有 'fields' 属性或 'exclude' 属性的 ModelForm;表单 ProductForm 需要更新。 我添加了“字段”,一切正常。谢谢。
  • 不幸的是 django-import-export 跳过了这个验证。还有什么技巧可以申请进口吗?
  • @GautamMandewalker 下次最好谈谈问题文本中的管理员集成库 :) 需要时间浏览库
猜你喜欢
  • 2014-05-21
  • 2012-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多