在Django中保存文件不起作用

时间:2016-01-09 15:58:47

标签: python django file-upload django-models filefield

我创建的form应该text,modelchoice and file。一切正常,而不是file保存。它不返回任何error但不保存任何文件。

所以这是我的表格:

class PurchaseForm(forms.Form):
    text = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 18, 'cols': 90}))
    language = forms.ModelChoiceField(queryset=Language.objects.all())
    file = forms.FileField(required=False)

这是一个名为job的模型:

class Job(models.Model):
    customer = models.ForeignKey(User,null=False,related_name='customer')
    freelancer = models.ForeignKey(User,null=True,related_name='freelancer')
    description = models.TextField(null=True)
    price = models.FloatField(null=True)
    language = models.ForeignKey(Language,null=False)
    file = models.FileField(upload_to='files')

这就是观点:

def purchase(request):
    if request.method == 'POST':
        print dict(request.POST.iterlists())
        form = forms.PurchaseForm(request.POST)
        if form.is_valid():
            job = Job()
            print form.cleaned_data
            job.customer = request.user
            job.language = form.cleaned_data['language']
            # job.description = form.cleaned_data['description']
            if 'file' in form.cleaned_data.keys():
                print 'OKOK'
                job.file = form.cleaned_data['file']
                # print job.file.path # If I uncomment this, it raises error Exception Value:   The 'file' attribute has no file associated with it.
            job.save()

            return render(request, 'purchases/complete.html')
    else:
        purchase_form = forms.PurchaseForm()
        return render(request, 'jobs/purchase.html', {'purchase_form': purchase_form})

在此view中有两个prints。第一个打印出来(我可以看到那里的文件):

{u'text': [u'\u010dr\u010dr\u010dr\u010d'], u'csrfmiddlewaretoken': [u'os8p9oRWR
d8mMTmSsGPd55Y7bWy6pMWl'], u'language': [u'3'], u'file': [u'export.csv']}

第二个打印出来:

{'text': u'\u010dr\u010dr\u010dr\u010d', 'file': None, 'language': <Language: HG
: Hungar - Intermediate - 0.02 eur/sign>}

就像我没有通过form上传(发送)任何文件一样。

你知道为什么会这样吗?

编辑:如果我将print job.file.path行取消注释,则会引发此错误:异常值:

The 'file' attribute has no file associated with it.

1 个答案:

答案 0 :(得分:1)

我认为你需要这样的更新表格:

def purchase(request):
    if request.method == 'POST':
        print dict(request.POST.iterlists())
        form = forms.PurchaseForm(request.POST request.FILES or None)

UPD评论:
保存尝试也可以在url中添加:

from django.conf.urls.static import static
urlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

并检查media设置:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

这是针对admin,为模型添加方法,使用图像字段:

def admin_image(self):
    return "<img src='%'/>" % self.your_image_field.url
    admin_image.allow_tags = True

并在list_display=('admin_image',)

中注册admin.py