django csv文件验证以模型形式清除方法

时间:2019-01-28 14:03:17

标签: django django-models django-forms django-views

以下是在我的Django应用程序中上传csv文件的FileModel:

class File(models.Model):
  uploaded_by = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
  )
  csv_file = models.FileField(
    upload_to='csvfiles/',
  )

在调用/upload_file url模式时,upload_csv_file视图执行如下:

 def upload_csv_file(request):
   if request.method == 'POST':
      csv_form = CSVForm(request.POST, request.FILES)
      if csv_form.is_valid():
        file_uploaded = csv_form.save(commit=False)
        file_uploaded.uploaded_by = request.user
        csv_form.save()
        return HttpResponse("<h1>Your csv file was uploaded</h1>")

   elif request.method == 'GET':
      csv_form = CSVForm()
      return render(request, './mysite/upload_file.html', {'csv_form': csv_form})

在forms.py中,我正在验证以下内容:

  • 文件扩展名(.csv)
  • 文件大小(5 mb)

    class CSVForm(forms.ModelForm):
    
      class Meta:
       model = File
       fields = ('csv_file',)
    
      def clean_csv_file(self):
       uploaded_csv_file = self.cleaned_data['csv_file']
    
       if uploaded_csv_file:
         filename = uploaded_csv_file.name
         if filename.endswith(settings.FILE_UPLOAD_TYPE):
            if uploaded_csv_file.size < int(settings.MAX_UPLOAD_SIZE):
                # return True
                  return uploaded_csv_file
            else:
                raise forms.ValidationError(
                    "Error")
        else:
            raise forms.ValidationError("Error")
    
      return uploaded_csv_file
    
      # no need for a separate def clean()
      # def clean(self):
        # cleaned_data = super(CSVForm, self).clean()
        # uploaded_csv_file = cleaned_data.get('csv_file')
        # return uploaded_csv_file
    

但是我在提交文件上传按钮时遇到以下错误:

  Attribute error: 'bool' object has no attribute 'get'

我不确定是否正在调用def clean_csv_file(self)

有多种方法可以在基于函数的视图中验证文件扩展名和大小,但是我想在ModelForm的clean()方法本身中验证文件属性。

请提出一个解决方案以应用相同的解决方案。谢谢!

更新:找到解决方案

def clean_csv_file(self)必须返回一个upload_csv_file变量的实例代替True。

此外,如果在ModelForm类中存在clean_field(),则不需要clean()方法。

1 个答案:

答案 0 :(得分:1)

您应该已经显示了完整的错误和追溯信息。

尽管如此,该错误是由您从clean_csv_file返回的内容引起的。清理函数的返回值必须始终是清理后的数据本身。对于clean_field方法,它必须是该字段的已清理数据,对于常规clean方法,它必须是完整的cleaned_data dict。所以:

def clean_csv_file(self):
   uploaded_csv_file = self.cleaned_data['csv_file']

   if uploaded_csv_file:
     filename = uploaded_csv_file.name
     if filename.endswith(settings.FILE_UPLOAD_TYPE):
        if uploaded_csv_file.size < int(settings.MAX_UPLOAD_SIZE):
            return uploaded_csv_file   # Here
        else:
            raise forms.ValidationError(
                "File size must not exceed 5 MB")
    else:
        raise forms.ValidationError("Please upload .csv extension files only")

  return uploaded_csv_file

请注意,您的clean方法也是错误的,但是更正后的版本(将返回cleaned_data)什么也不做,因此您应该删除整个内容。