Django Imagefield 无法通过 ModelForm 正常工作 [英] Django Imagefield not working properly via ModelForm

查看:30
本文介绍了Django Imagefield 无法通过 ModelForm 正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定我在做的事情显然很愚蠢,但我已经尝试弄清楚几个小时了,但没有任何反应.

I'm certain I'm doing something really obviously stupid, but I've been trying to figure it out for a few hours now and nothing is jumping out at me.

我正在使用 ModelForm,因此我可以从模型中公开一些字段以进行编辑.2x 图像字段,1x 文本字段.表单被处理,TextField 工作.这两个 ImageField 不起作用,这就是我今天在这里的原因.

I'm using a ModelForm so I can expose a few fields from a model for editing. 2x ImageField, 1x TextField. The Form is processed and the TextField works. The two ImageFields do not work and they're why I'm here today.

我使用的是 Django 1.0.2

I'm using Django 1.0.2

这是相关的代码(询问您是否需要更多——我不包括 HTML,因为该部分似乎工作正常):

Here's the relevant code (ask if you need more -- and I'm not including the HTML because that part appears to work fine):

型号:

class Company(models.Model):
    #...
    logo = models.ImageField(upload_to='logos', blank=True)
    intro_pic = models.ImageField(upload_to='intropics', blank=True)
    intro_text = models.TextField(blank=True)

查看和表单:

def admin_edit(request, company_slug):
    company = get_object_or_404(Company, slug = company_slug)

    f = AdminEditForm(instance = company)
    if request.method == 'POST':
        f = AdminEditForm(request.POST, instance = company)
        if f.is_valid():
            print "Processing form"
            print f.cleaned_data['intro_pic']
            f.save()

    return render_to_response('uadmin/edit.html', {'company':company, 'f':f}, RequestContext(request))


class AdminEditForm(ModelForm):
    class Meta:
        model = Company
        fields = ['logo', 'intro_pic', 'intro_text']

推荐答案

我觉得自己像个白痴.为了让 Django 能够处理上传的文件,您需要将 request.FILES 变量传递给表单(有意义,对吧?!)

Well I feel like an idiot. In order for Django to be able to process uploaded files, you need to pass the request.FILES variable to the form (makes sense, right?!)

就我而言,以下行来自:

In my case the following line goes from:

f = AdminEditForm(request.POST, instance = company)

致:

f = AdminEditForm(request.POST, request.FILES, instance = company)

要检查的另一件事(如果您将来遇到类似的情况)是您的表单是多部分的.你的

标签应该是这样的:

Another thing to check (if you run into something like this in the future) is that your form is multipart. Your <form> tag should look something like this:

<form enctype="multipart/form-data" method="post" action="">

这篇关于Django Imagefield 无法通过 ModelForm 正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆