【问题标题】:Django csv file validation in model form clean method模型表单清理方法中的 Django csv 文件验证
【发布时间】:2019-06-21 13:16:02
【问题描述】:

以下是在我的 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() 方法。

【问题讨论】:

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


    【解决方案1】:

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

    但是,由您从clean_csv_file 返回的内容引起的错误。清理函数的返回值必须始终是清理后的数据本身;对于 clean_field 方法,它必须是该字段的已清理数据,而对于一般 clean 方法,它必须是完整的 clean_data 字典。所以:

    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)根本没有任何作用,因此您应该删除整个内容。

    【讨论】:

    • 是的,谢谢!有用。虽然我想知道只定义 clean() 是否就足够了?
    猜你喜欢
    • 1970-01-01
    • 2012-01-28
    • 2012-02-22
    • 2011-04-22
    • 1970-01-01
    • 2018-05-10
    • 2020-06-22
    • 2016-04-16
    • 1970-01-01
    相关资源
    最近更新 更多