Django Imagefield not working properly via ModelForm

我怕爱的太早我们不能终老 提交于 2019-12-31 08:04:19

问题


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.

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.

I'm using Django 1.0.2

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

Model:

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)

View and form:

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']

回答1:


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)

To:

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="">


来源:https://stackoverflow.com/questions/680770/django-imagefield-not-working-properly-via-modelform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!