为什么我可以保存文件,但django中没有其他形式的文件?

时间:2014-01-24 19:18:48

标签: python django django-forms django-views

我有一些代码正在引发MultiValueDictKeyError,我只是想了解为什么会发生这种情况。保存文件时一切正常;然而,当我尝试添加更多数据时,错误弹出。

我必须警告你,我非常喜欢django / python /编程。对此的任何帮助都将帮助我理解如何在Django中正确实例化表单。



模特(工作):

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')

    def __unicode__(self):
        return self.first_name


表格(工作):

from django import forms
from django.forms import ModelForm
from .models import Document

class DocumentForm(forms.ModelForm):
    docfile = forms.FileField(label='Select a file',)

    class Meta:
        model = Document


观点(工作):

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from .models import NewDocument, Document
from .forms import NewDocumentForm, DocumentForm

import time


def list(request):    
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)        
        if form.is_valid():
#            newdoc = Document(docfile = request.FILES['docfile']) #simplified version
            f_docfile = request.FILES['docfile']
            newdoc = Document(docfile=f_docfile)
            newdoc.save()

            return HttpResponseRedirect(reverse('uploadtest.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form    

    return render_to_response(
        'uploadtest/list.html',
        {'form': form},
        context_instance=RequestContext(request)
    )


模板(工作)

<div class="section">


        <!-- Upload form. Note enctype attribute! -->
        <form action="{% url "list" %}" method="post" enctype="multipart/form-data">
            {% csrf_token %}

            <p>{{ form.non_field_errors }}</p>
            <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
            <p>
                {{ form.docfile.errors }}
                {{ form.docfile }}
            </p>

            <p><input type="submit" value="Submit" /></p>
        </form>
</div>  






模特(不工作)

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class NewDocument(models.Model):
    user = models.ForeignKey(User)
    timestamp = models.DateTimeField(auto_now_add=True)
    part = models.CharField(max_length=255)
    description = models.CharField(max_length=255)
    analysis = models.TextField()
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')


表格(不工作)

from django import forms
from django.forms import ModelForm
from .models import NewDocument, Document

class NewDocumentForm(forms.ModelForm):
    docfile = forms.FileField(label='Select a file',)

    class Meta:
        model = NewDocument


观点(不工作)

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from .models import NewDocument, Document
from .forms import NewDocumentForm, DocumentForm

import time


def list(request):  
    if request.method == 'POST':
    #import pdb
    #pdb.set_trace()
        form = NewDocumentForm(request.POST, request.FILES)
        if form.is_valid():
            f_user = request.user
            f_timestamp = str(int(time.time()))
            f_part = request.POST['part']
            f_description = request.POST['description']
            f_analysis = request.POST['analysis']
            f_docfile = request.FILES['docfile']
            newdoc = NewDocument(user=f_user, timestamp=f_timestamp, part=f_part, description=f_description, analysis=f_analysis, docfile=f_docfile)
            newdoc.save()

            return HttpResponseRedirect(reverse('uploadtest.views.list'))
    else:
        form = NewDocumentForm() # A empty, unbound form    

    return render_to_response(
        'uploadtest/list.html',
        {'form': form},
        context_instance=RequestContext(request)
    )


模板(不工作)

<div class="section">


        <!-- Upload form. Note enctype attribute! -->
        <form action="{% url "list" %}" method="post" enctype="multipart/form-data">
            {% csrf_token %}

            <li>            
            <p><label for="id_part">Part</label>
            <input id="id_part" type="text" name="part" maxlength="255" /></p>

            <p><label for="id_description">Description</label>
            <input id="id_description" type="text" name="description" maxlength="255" /></p>            
            </li>

            <p><label for="id_analysis">Analysis</label>
            <input id="id_analysis" type="text" name="analysis" maxlength="" /></p> 

            <p>{{ form.non_field_errors }}</p>
            <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
            <p>
                {{ form.docfile.errors }}
                {{ form.docfile }}
            </p>

            <p><input type="submit" value="Submit" /></p>
        </form>
</div>  



感谢您的帮助!




我继续乱用pdb,这就是我得到的。这有用吗?

-> try:
(Pdb) 
> /Users/tehspacecadet_air/newenv/lib/python2.7/site-packages/django/utils/datastructures.py(293)__getitem__()
-> list_ = super(MultiValueDict, self).__getitem__(key)
(Pdb) s
KeyError: ('user',)
> /Users/tehspacecadet_air/newenv/lib/python2.7/site-packages/django/utils/datastructures.py(293)__getitem__()
-> list_ = super(MultiValueDict, self).__getitem__(key)
(Pdb) 
> /Users/tehspacecadet_air/newenv/lib/python2.7/site-packages/django/utils/datastructures.py(294)__getitem__()
-> except KeyError:
(Pdb) 
> /Users/tehspacecadet_air/newenv/lib/python2.7/site-packages/django/utils/datastructures.py(295)__getitem__()
-> raise MultiValueDictKeyError("Key %r not found in %r" % (key, self))
(Pdb) 
--Call--
> /Users/tehspacecadet_air/newenv/lib/python2.7/site-packages/django/utils/datastructures.py(283)__repr__()
-> def __repr__(self):
(Pdb) 
> /Users/tehspacecadet_air/newenv/lib/python2.7/site-packages/django/utils/datastructures.py(284)__repr__()
-> return "<%s: %s>" % (self.__class__.__name__,
(Pdb) 
> /Users/tehspacecadet_air/newenv/lib/python2.7/site-packages/django/utils/datastructures.py(285)__repr__()
-> super(MultiValueDict, self).__repr__())
(Pdb) 
--Return--
> /Users/tehspacecadet_air/newenv/lib/python2.7/site-packages/django/utils/datastructures.py(285)__repr__()->"<QueryDict: ...: [u'What']}>"
-> super(MultiValueDict, self).__repr__())
(Pdb) 
MultiValueDictKeyError: MultiVal...at']}>",)
> /Users/tehspacecadet_air/newenv/lib/python2.7/site-packages/django/utils/datastructures.py(295)__getitem__()
-> raise MultiValueDictKeyError("Key %r not found in %r" % (key, self)) 

2 个答案:

答案 0 :(得分:0)

这可能意味着您的request.POST中缺少其中一个字段。 您可以在将request.POST字典传递给NewDocumentForm之前记录它吗?

答案 1 :(得分:0)

引发“MultiValueDictKeyError”,因为您的request.POST中存在字段不匹配以及您在forms.py中声明的字段

例如,您的forms.py中缺少“part”,“description”,“analysis”声明

希望这可以修复错误