3

以下是我的模型:

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')

我想在保存之前对product_offer_price字段进行验证,为此我发布了一个QUESTION并通过有效的解决方案得到了回答。

需要的验证是:

 if product_offer_price > product_mrp:
    raise ValidationError

现在,上述问题的解决方案非常适用于管理表单。

但是,我已经实现了 django-import-export,我在管理员中批量导入产品数据,并且在批量导入期间我需要类似的验证。

如何做到这一点?

4

3 回答 3

3

好吧,这里有一个小小的研究过程。

最后我明白了。

麻烦在于避免在导入导出库中使用 ProductForm。在实例的库导入调用方法 save() 内部,但是如果我们在模型(不在表单中)中引发 ValidationError = 500 且 DEBUG = False,并且追溯页面使用 DEBUG = True。所以我们应该在 import_export 资源中使用“before_import”方法,在 django.forms 表单中使用“clean”方法。

管理员.py

from forms import ProductForm
from models import Product
from import_export import resources
from import_export.admin import ImportExportActionModelAdmin
from django.forms import ValidationError

class ProductResource(resources.ModelResource):

    class Meta:
        model = Product

    def before_import(self, dataset, using_transactions, dry_run, **kwargs):
        for row in dataset:
            if int(row[4]) < int(row[5]):
                raise ValidationError('Product offer price cannot be greater than Product MRP. '
                                      'Error in row with id = %s' % row[0])


class ProductAdmin(ImportExportActionModelAdmin):
    list_display = ('product_title', 'product_description', 'product_qty', 'product_mrp', 'product_offer_price')
    form = ProductForm
    resource_class = ProductResource


admin.site.register(Product, ProductAdmin)

表格.py

from django import forms
from models import Product


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

模型.py

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')
于 2017-09-07T14:08:22.063 回答
2

before_import_row一种更简单的方法可能是通过向资源类添加自定义方法来挂钩导入/导出工作流程:

class ProductResource(resources.ModelResource):

    class Meta:
        model = Product

    def before_import_row(self, row, **kwargs):
        if int(row[4]) < int(row[5]):
            raise ValidationError('Product offer price cannot be greater than Product MRP. '
                                  'Error in row with id = %s' % row[0])
于 2019-07-15T13:30:45.050 回答
-1

这是 Django Rest 框架的另一种简单方法

def importcsv(request, company):
        for row in dataset['company']:
            if(row != company):
            raise PermissionDenied("You do not have permission to Enter Clients in Other Company, Be Careful")
于 2018-12-05T17:34:50.493 回答