Пытаюсь сделать загрузку изображения в Django.
Создаю класс в модели с полем FileField:
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=False)
picture = models.FileField(upload_to='media/images/', blank=True, null=True)
def __unicode__(self):
return unicode(self.picture.name)
в forms.py:
class ProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['picture']
во view.py:
def signup(request, user_id=None, template_name='signup.html'):
...
if request.method == 'POST':
...
profileForm = ProfileForm(request.POST, request.FILES)
if profileForm.is_valid():
print("profileForm is valid!")
print(request.POST)
pic = UserProfile(picture=request.FILES['picture'])
pic = profileForm.save(commit=False)
pic.user = request.user
pic.save()
message = "File %s is uploaded" % pic
print(message)
else:
print("NOT VALID!")
и шаблон:
<form action="" method="POST" enctype="multi-part/formdata">
<table>
{{ profileForm.as_table }}
</table>
{% csrf_token %}
<input type="submit" name="submit" value="Submit">
</form>
ругается на:
request.FILES['picture']
Traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/user/1/edit/
Django Version: 1.6.1
Python Version: 3.3.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Python33\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Django\sandpit\blog\views.py" in signup
147. pic = UserProfile(picture=request.FILES['picture'])
File "C:\Python33\lib\site-packages\django\utils\datastructures.py" in __getitem__
301. raise MultiValueDictKeyError(repr(key))
Exception Type: MultiValueDictKeyError at /user/1/edit/
Exception Value: "'picture'"
Хотя в QueryDict показывает имя файла:
<QueryDict: ... , 'picture': ['2.jpeg'], ... >
Подскажите, пожалуйста, что не так?