我正在尝试验证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 --魔术安装错误--无法找到lib魔术。所以我想不带魔法的去做。
任何帮助/建议/链接都将受到高度赞赏。提前谢谢。
发布于 2017-09-02 17:12:54
您可以创建一个自定义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])发布于 2017-09-02 17:13:55
只需将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 filehttps://stackoverflow.com/questions/46016222
复制相似问题