如何在django-import-export中进行字段验证 [英] How to do field validation in django-import-export

查看:489
本文介绍了如何在django-import-export中进行字段验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的模特:

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 字段进行验证,为此我发布了

I wanted to have a validation for product_offer_price field before save for which I had posted a QUESTION and it was answered with the working solution.

所需的验证是:

 if product_offer_price > product_mrp:
    raise ValidationError

现在,上述问题的解决方案非常适合管理表单.

Now the solution to above question works perfectly for the admin forms.

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

But, I have implemented django-import-export, in which I am importing Product Data in bulk in admin, and I need similar validation during bulk import.

如何实现?

推荐答案

嗯,这是一个小研究过程.

Well, here was a little research process.

最后我明白了.

问题在于避免在导入导出库中使用ProductForm. 在库导入内部调用实例的方法save(),但是如果我们在DEBUG = False时在Model(不在Form中)= 500中引发ValidationError,而在DEBUG = True时回溯页面. 因此,我们应该在import_export资源中使用"before_import"方法,在django.forms表单中使用"clean"方法.

The trouble is avoiding ProductForm in import-export library. Inside library import invoke method save() of instance, but if we raise ValidationError in Model (not in Form) = 500 with DEBUG = False, and traceback page with DEBUG = True. So we should use "before_import" method in import_export Resource and "clean" method in django.forms Form.

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

这篇关于如何在django-import-export中进行字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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