1

我正在使用 Django 导入和导出以及从.xls文件导入数据,现在我想验证 col 2 值不应为空,因为我使用了以下代码,但它适用于管理站点,而不适用于数据从外部文件上传。

class CTSResource(resources.ModelResource):
   class meta:
      Model=CTA
   def before_import(self, dataset, using_transactions, dry_run, **kwargs):
      for col in dataset:
         if col[2] == '':

            raise ValidationError('This field black. '
                                  'Error in row with id = %s' % col[2])

如何在 .xls 文件级别应用此验证。是否可以在文件处理级别检查这是我的上传视图代码。

def CTA_upload(request):
    try:
        if request.method == 'POST':
            movie_resource = CTAResource()
            ##we will get data in movie_resources####
            dataset = Dataset()
            new_movie = request.FILES['file']
            if not new_movie.name.endswith('xls'):
                messages.info(request, 'Sorry Wrong File Format.Please Upload valid format')
                return render(request, 'apple/uploadinfosys.html')
            messages.info(request, 'Uploading Data Line by Line...')
            imported_data = dataset.load(new_movie.read(), format='xls')
            count = 1
            for data in imported_data:
                value = CTA(
                    data[0],
                    data[1],
                    data[2],
                    data[3],
                    data[4],
                    data[5],
                    data[6],
                    data[7],
                    data[8],
                )
                count = count + 1
                value.save()
                # messages.info(request, count)
            # time.sleep(1)
            messages.info(request, 'File Uploaded Successfully...')
            
    except:
        messages.info(request,'Same Email ID has been observed more than once.Except that other records has been added../nPlease Make sure Email field should be unique.')
    
    return render(request,'app/cta.html')

如何进行字段级验证。

4

0 回答 0