Python Django中的文件上载类型验证

Python Django中的文件上载类型验证,python,django,Python,Django,我正在尝试验证Django中的上载文件类型功能。允许的扩展只能是xml。管理员将上载一个xml文件,然后用xml文件中的数据填充该表。模型没有文件字段,但表单有 accounts/models.py-- accounts/forms.py-- settings.py UPLOAD_PATH = os.path.join(BASE_DIR, "static", "uploads") CONTENT_TYPES = ['xml'] MAX_UPLOAD_SIZE = "2621440" clas

我正在尝试验证Django中的上载文件类型功能。允许的扩展只能是xml。管理员将上载一个xml文件,然后用xml文件中的数据填充该表。模型没有
文件字段
,但表单有

accounts/models.py
--

accounts/forms.py
--

settings.py

UPLOAD_PATH = os.path.join(BASE_DIR, "static", "uploads")

CONTENT_TYPES = ['xml']
MAX_UPLOAD_SIZE = "2621440"
class couplingAdmin(admin.ModelAdmin):
    list_display = ('coupling_name','module_name')
    form = CouplingUploadForm
admin.site.register(Coupling, couplingAdmin)
import os 

def clean_coupling_file(self):
    file = self.cleaned_data['coupling_file']
    extension = os.path.splitext(file.name)[1]  # [0] returns path+filename
    VALID_EXTENSION = '.xml'

    if extension != VALID_EXTENSION:
        self.add_error(
            'coupling_file',
            _('Only files with ".xml" extension are supported, '
              'received: "%s" file.' % extension)
        )
    return file
accounts/admin.py

UPLOAD_PATH = os.path.join(BASE_DIR, "static", "uploads")

CONTENT_TYPES = ['xml']
MAX_UPLOAD_SIZE = "2621440"
class couplingAdmin(admin.ModelAdmin):
    list_display = ('coupling_name','module_name')
    form = CouplingUploadForm
admin.site.register(Coupling, couplingAdmin)
import os 

def clean_coupling_file(self):
    file = self.cleaned_data['coupling_file']
    extension = os.path.splitext(file.name)[1]  # [0] returns path+filename
    VALID_EXTENSION = '.xml'

    if extension != VALID_EXTENSION:
        self.add_error(
            'coupling_file',
            _('Only files with ".xml" extension are supported, '
              'received: "%s" file.' % extension)
        )
    return file
我已经阅读了一些SOF参考资料,其中大多数都有
model.FileField
,但我不想将文件保存在model中

我尝试使用magic——但是我遇到了一个python magic安装错误——找不到libmagic。所以我想不用魔法


非常感谢您的任何帮助/建议/链接。提前感谢。

您可以创建自定义的
验证程序

def validate_file_extension(value):
    import os
    from django.core.exceptions import ValidationError
    ext = os.path.splitext(value.name)[1]
    valid_extensions = ['.xml']
    if not ext.lower() in valid_extensions:
        raise ValidationError(u'Unsupported file extension.')
然后在表单字段中

coupling_file = forms.FileField(label='XML File Upload:',
                               required=True, validators=[validate_file_extension])

只需在
forms.py中编写一个
clean
方法

UPLOAD_PATH = os.path.join(BASE_DIR, "static", "uploads")

CONTENT_TYPES = ['xml']
MAX_UPLOAD_SIZE = "2621440"
class couplingAdmin(admin.ModelAdmin):
    list_display = ('coupling_name','module_name')
    form = CouplingUploadForm
admin.site.register(Coupling, couplingAdmin)
import os 

def clean_coupling_file(self):
    file = self.cleaned_data['coupling_file']
    extension = os.path.splitext(file.name)[1]  # [0] returns path+filename
    VALID_EXTENSION = '.xml'

    if extension != VALID_EXTENSION:
        self.add_error(
            'coupling_file',
            _('Only files with ".xml" extension are supported, '
              'received: "%s" file.' % extension)
        )
    return file

仅仅因为文件具有
.xml
扩展名,并不意味着它是xml文件。如果希望安全,还需要验证内容。这可能会在以后代码中断时隐式发生,但最好确定一下。你完全正确,但我认为,由于此功能仅适用于管理员,因此没有人会试图强制中断它。然而,即使我们允许
.xml
文件,潜在的中断也应该在导入级别处理,而不是表单。总有可能是一个好的文件,其中包含损坏的内容,而且可能不是故意的。我想我必须在
pythonpath
中添加
django.conf
。获取错误
ImportError:没有名为'django.conf.settings'的模块可以正常工作。非常感谢。@PrithvirajMitra此链接docs.djangoproject.com/en/dev/ref/validators/…如果您使用的是Django 1.11,也会对您有所帮助。请投票或接受答案,如果它对你有帮助的话。什么是代码作为参数?要检查内部内容?@PrithvirajMitra Well validatior是一种标准的东西,您可以使用单个validatior函数以多种形式使用。