【问题标题】:How to do field validation in django-import-export如何在 django-import-export 中进行字段验证
【发布时间】:2017-09-04 15:10:39
【问题描述】:

以下是我的模型:

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,我在管理员中批量导入产品数据,并且在批量导入期间我需要类似的验证。

如何做到这一点?

【问题讨论】:

  • 那里有错字吗?在预筹空间? 8 代替 4)
  • 是的,已更正。我只是想举例说明需要什么验证以及在哪个字段上。
  • 在模型的clean() 方法中进行验证。这应该涵盖来自管理站点的验证和来自任何视图的验证。如果您没有 clean() 方法,请创建并覆盖一个 - clean() 是您所有模型的超级方法。
  • @GautamMandewalker 检查答案)
  • 是的,在我的应用程序上进行测试。有时间会更新。

标签: django django-admin django-import-export


【解决方案1】:

嗯,这是一个小小的研究过程。

我终于明白了。

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

admin.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)

forms.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

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

【讨论】:

  • 这适用于新项目和应用程序,但不适用于我现有的应用程序。我不明白为什么。在现有应用程序中,验证完全被跳过。我会接受你的回答。
【解决方案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])

【讨论】:

    【解决方案3】:

    这是 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")
    

    【讨论】:

      猜你喜欢
      • 2015-05-08
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多