I want to set an optional imagefield in my django models. I set blank=True, null=True in the imagefields.After inputting the below codes I input an image in all the imagefield except place_4_view. After clicking on the upload button, I’m getting an error. What I’m I missing?
Models
class Findme(models.Model):
place_2_view=models.ImageField(upload_to="photos",blank=True,null=True)
place_3_view=models.ImageField(upload_to="photos",blank=True,null=True)
place_4_view=models.ImageField (upload_to="photos",blank=True,null=True,help_text='Optional.')
Error when uploading
Request Method: POST
Request URL: http://127.0.0.1:8000/find/
Django Version: 1.4
Exception Type: MultiValueDictKeyError
Exception Value: "Key 'place_4_view' not found in <MultiValueDict: {u'place_2_view': [<TemporaryUploadedFile: 2012-05-17-289.jpg (image/jpeg)>], u'place_3_view': [<TemporaryUploadedFile: Crimo.JPG (image/jpeg)>]}>"
Exception Location: C:\Python27\lib\site-packages\django\utils\datastructures.py in __getitem__, line 258
Python Executable: C:\Python27\python.exe
Views
def findpic(request):
extra_data_context={}
#if there's nothing in the field do nothing.
if request.method=="POST":
form=FindmeForm(request.POST, request.FILES)
if form.is_valid():
data=form.cleaned_data
newfindmes=Findme(
user=request.user,
pub_date=datetime.datetime.now(),
place_2_view=request.FILES['room_2_view'],
place_3_view=request.FILES['room_3_view'],
place_4_view=request.FILES['room_4_view'])
newfindmes.save()
extra_data_context.update({'FindmeForm':form})
else:
form = FindmeForm()
extra_data_context.update({'FindmeForm':form})
extra_data_context.update({'Findmes':Findme.objects.filter(user=request.user)})
return render_to_response('postme.html',extra_data_context,context_instance=RequestContext(request))
Template
{% block content %}
<form enctype="multipart/form-data" form action="." method="POST">
{% csrf_token %}
<div class="post-fed">{{ FindmeForm.as_p}}</div>
<input type="submit" value="Get It"/>
</form>
{% for Findme in Findmes.object_list %}
<tr>
<p> {{Findme.pub_date|timesince }} ago </p>
<p><img src="{{Findme.thumbnail_2.url}}" width="83" height="78">
<img src="{{Findme.thumbnail_3.url}}" width="83" height="78"> {% if Findme.thumbnail_4 %} <img src="{{Findme.thumbnail_4.url}}" width="83" height="78"/>
{% endif %}
<p> Created By {{ Findme.user }}</p>
{% endfor %}
{% endblock %}
It appears that you have code that expects the key to be in the form during form submission.
Edit:
Your findPic method is trying to get the field and the field isn’t there when it is empty. I would recommend the use of request.FILES.get And specify a default value, or test request.FILES for the presence of the keys, or iterate over the keys themselves. Basically your code needs to be prepared for request.FILES To be empty or not contain all the fields you are trying to access.
See this answer for an example of using request.FILES.get and Files Django Docs for other details on the request.FILES object.