我正在尝试验证Django中的上传文件类型功能。允许的扩展名仅为xml。管理员将上传一个xml文件,然后将使用xml文件中的数据填充该表。该模型没有filefield
,但表单有。
accounts/models.py
-
class Coupling(models.Model):
coupling_name = models.CharField(max_length=150, blank=False, null=True, default="")
module_name = models.TextField(blank=False, null=True)
def __str__(self):
return self.coupling_name
class Meta:
verbose_name_plural = "Couplings"
accounts/forms.py
-
class CouplingUploadForm(forms.ModelForm):
coupling_file = forms.FileField(label='XML File Upload:', required=True)
class Meta:
model = models.Coupling
exclude = ['coupling_name', 'module_name']
settings.py
UPLOAD_PATH = os.path.join(BASE_DIR, "static", "uploads")
CONTENT_TYPES = ['xml']
MAX_UPLOAD_SIZE = "2621440"
accounts/admin.py
class couplingAdmin(admin.ModelAdmin):
list_display = ('coupling_name','module_name')
form = CouplingUploadForm
admin.site.register(Coupling, couplingAdmin)
我已经浏览了一些SOF参考文献,其中大多数都有model.FileField
,但在我的情况下,我不想将文件保存在模型中。
我尝试使用魔法 - https://djangosnippets.org/snippets/3039/但我得到了一个python-magic安装错误 - 无法找到libmagic。所以我想在没有魔法的情况下这样做。
非常感谢任何帮助/建议/链接。提前谢谢。
答案 0 :(得分:3)
只需在clean
forms.py
方法即可
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
答案 1 :(得分:1)
您可以创建自定义validator
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])