Django表格与fileupload

时间:2015-02-08 02:03:22

标签: django django-forms django-file-upload

我通过表格上传文件,撞到墙上。通过管理员上传一切正常。使用模型时,它会重新加载带有文件字段空白的表单和错误消息"此字段是必需的。"

这是模型

class DefaultPage(models.Model):
title = models.CharField(max_length=100)
created_date = models.DateTimeField(auto_now_add=True, auto_now=False)
edited_date =  models.DateTimeField(auto_now_add=False,auto_now=True)
parent_page = models.ForeignKey("self",blank=True, null=True)
slug = models.SlugField(max_length=100,editable=False,blank=True)
def __unicode__ (self): 
    return self.title
def save(self, *args, **kwargs):
    if not self.id:
        self.slug = slugify(self.title)
    super(DefaultPage, self).save(*args, **kwargs)

class LearningObject(DefaultPage):
archivefile = models.FileField(upload_to='static/learningobject/archivefiles/%Y/%m/%d')
indexpath = models.CharField(max_length=254,editable=False)
def unpackarchive(self):
    archive = self.archivefile
    filename = os.path.basename(str(archive))

    folder = str(filename).split(".")[0]
    print folder
    index_found = "False"
    with zipfile.ZipFile(archive,"r") as z:
        for each in z.namelist():
            if each == "index.html" or each == "index.htm":
                index_found = "True"
            else:
                pass
        if not index_found:
            print "zip file does not contain a valid index.html file"
        else:
            path = os.path.join("static","learningobject","unpackedarchives",folder)
            z.extractall(path)
            self.findindex(path)
def findindex(self,path):

    print path
    for root, dirnames, filenames in os.walk(path):
        for filename in fnmatch.filter(filenames, 'index.ht*'):
            print filename
            self.indexpath = os.path.join(root, filename)
    print self.indexpath

def save(self, *args, **kwargs):
    self.unpackarchive()
    super(LearningObject, self).save(*args, **kwargs)

这是视图

def learningobject_form(request, parent_page_id):
print 
if request.method == 'GET':
    form = LearningObjectForm()
else:
    form = LearningObjectForm(request.POST, request.FILES)
    if form.is_valid():
        learningobject = request.FILES['archivefile']
        title = form.cleaned_data['title']
        parent_page = DefaultPage.objects.get(pk=parent_page_id)
        post = Page.objects.create(archivefile=learningobject,title=title,parent_page=parent_page)

        return HttpResponseRedirect(reverse('index', ))
return render(request, 'wiki/learningobject_form.html', {'form': form,})

这是表格

class LearningObjectForm(forms.ModelForm):
class Meta:
    model = LearningObject
    fields = ['title','archivefile']

和模板

<form action='' method='post'>{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Submit' />

0 个答案:

没有答案