Django Imagefield not working properly through ModelForm

I am sure that I am doing something really obviously stupid, but I tried to figure it out for several hours and nothing jumps at me.

I use ModelForm, so I can set several fields from the model for editing. 2x ImageField, 1x TextField. The form is being processed and the TextField is working. Two ImageFields do not work, which is why I am here today.

I am using Django 1.0.2

Here is the relevant code (ask if you need more - and I don’t include HTML, because this part works 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'] 
+42
django django-models django-forms
Mar 25 '09 at 9:06
source share
1 answer

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

In my case, the following line comes from:

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

To:

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

Another thing to check (if you come across something similar in the future) is that your form is multi-part. The <form> should look something like this:

 <form enctype="multipart/form-data" method="post" action=""> 
+97
Mar 25 '09 at 13:44
source share



All Articles