3

我的 html 页面中有一个表单,提示用户将文件或图像上传到服务器。我希望能够上传以太文件或图像。假设用户选择文件,图像应该为空,反之亦然。现在我只能上传他们两个,没有错误。但是如果我选择只上传其中一个(假设我选择图片),我会收到一个错误:

"Key 'attachment' not found in <MultiValueDict: {u'image': [<InMemoryUploadedFile: police.jpg (image/jpeg)>]}>"

在此处输入图像描述

模型.py:

#Description of the file 
class FileDescription(models.Model):

    TYPE_CHOICES = (
        ('homework', 'Homework'),
        ('class', 'Class Papers'),
        ('random', 'Random Papers')                    
    )

    subject = models.ForeignKey('Subjects', null=True, blank=True)
    subject_name = models.CharField(max_length=100, unique=False)

    category = models.CharField(max_length=100, unique=False, blank=True, null=True)

    file_type = models.CharField(max_length=100, choices=TYPE_CHOICES, unique=False) 
    file_uploaded_by = models.CharField(max_length=100, unique=False)
    file_name = models.CharField(max_length=100, unique=False)
    file_description = models.TextField(unique=False, blank=True, null=True)
    file_creation_time = models.DateTimeField(editable=False)
    file_modified_time = models.DateTimeField()

    attachment = models.FileField(upload_to='files', blank=True, null=True, max_length=255)
    image = models.ImageField(upload_to='files', blank=True, null=True, max_length=255)

    def __unicode__(self):
        return u'%s' % (self.file_name)

    def get_fields(self):
        return [(field, field.value_to_string(self)) for field in FileDescription._meta.fields]

    def filename(self):
        return os.path.basename(self.image.name)

    def category_update(self):
        category = self.file_name
        return category

    def save(self, *args, **kwargs):
        if self.category is None:
            self.category = FileDescription.category_update(self)
        for field in self._meta.fields:
            if field.name == 'image' or field.name == 'attachment':
                field.upload_to = 'files/%s/%s/' % (self.file_uploaded_by, self.file_type)
        if not self.id:
            self.file_creation_time = datetime.now()
        self.file_modified_time = datetime.now()
        super(FileDescription, self).save(*args, **kwargs)

表格.py

class ContentForm(forms.ModelForm):
    file_name =forms.CharField(max_length=255, widget=forms.TextInput(attrs={'size':20}))
    file_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':25}))

    class Meta:
        model = FileDescription 
        exclude = ('subject',
                   'subject_name',
                   'file_uploaded_by',
                   'file_creation_time',
                   'file_modified_time',
                   'vote')

    def clean_file_name(self):
        name = self.cleaned_data['file_name']
        # check the length of the file name
        if len(name) < 2:
            raise forms.ValidationError('File name is too short')
        # check if file with same name is already exists
        if FileDescription.objects.filter(file_name = name).exists():
            raise forms.ValidationError('File with this name already exists')
        else:
            return name

视图.py

if request.method == "POST":
        if "upload-b" in request.POST:
            form = ContentForm(request.POST, request.FILES, instance=subject_id)       
            if form.is_valid(): # need to add some clean functions
               # handle_uploaded_file(request.FILES['attachment'],
               #                      request.user.username,
               #                      request.POST['file_type'])
                form.save()
                up_f = FileDescription.objects.get_or_create(
                    subject=subject_id,
                    subject_name=subject_name,
                    category = request.POST['category'],
                    file_type=request.POST['file_type'],
                    file_uploaded_by = username,
                    file_name=form.cleaned_data['file_name'],
                    file_description=request.POST['file_description'],
                    image = request.FILES['image'],
                    attachment = request.FILES['attachment'],
                )
                return HttpResponseRedirect(".")
4

3 回答 3

2

假设用户选择文件,图像应该为空,反之亦然。

你可以:

  1. 做一个 SQL 约束,

  2. model.save()如果文件或图像为空白,则覆盖失败,

  3. 如果文件或图像为空白,请定义ContentForm.clean()引发 a ,请参阅清理和验证相互依赖的字段ValidationError

还要注意 up_f 将是一个元组:

up_f = FileDescription.objects.get_or_create(
于 2012-09-10T15:52:43.237 回答
0

我有同样的问题。由于某种原因,键值字典仅采用一个键对值。像这样保存附件

附件=form.data['附件']

附件=request.FILES['附件']

它应该运行,但很好奇它是否会保存为文件。
我知道这个问题很老,但遇到同样的问题很困难

于 2013-11-07T21:09:33.523 回答
0

为用户创建单选按钮以选择他/她要上传的内容,并在模型中仅使用一个 FileField 属性。您可以将其他字段转换为 BooleanField 或 CharField 以指示用户选择的内容。

于 2016-08-29T12:48:20.487 回答