2012-09-10 42 views
3

我在我的html頁面中有一個表單,它提示用戶上傳文件或圖像到服務器。我想能夠上傳以太文件或圖像。比方說,如果用戶選擇文件,圖像應該是空的,反之亦然。現在我只能上傳他們兩個,沒有錯誤。但如果我選擇上傳只是其中之一(比方說,我選擇的圖像),我會得到一個錯誤:Django,要上傳圖像(ImageField)或文件(FileField)

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

enter image description here

models.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) 

forms.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 

views.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(".") 

回答

2

Let's say if user choose file, image should be null, and vice verso.

您可以:

  1. 作出SQL約束,

  2. 覆蓋model.save()到如果任何文件或圖像是空白的失敗,

  3. 定義ContentForm.clean()提出一個ValidationError如果文件或圖像是空白的,請參閱Cleaning and validating fields that depend on each other

另外要注意的是up_f將是一個元組:

up_f = FileDescription.objects.get_or_create(
0

我有同樣的問題。由於某些原因,鍵值字典只需要一個密鑰對值。保存像這樣

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

的附件,而不是

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

它應該運行,但好奇,如果它將保存爲一個文件。
我知道這個問題是舊的,但同時遇到困難

0

爲用戶創建單選按鈕以選擇他/她想要上傳的內容,並在模型中只使用一個FileField屬性。您可以將其他字段轉換爲BooleanField或CharField以指示用戶選擇的內容。

相關問題