我一直只是尝试上传个人资料图片,这是我之前所做的。但是这次,即使代码相同,文件也没有上传。可以从request.data('image')
访问图像名称,但是不能从request.FILES['image']
我也尝试了序列化程序,表格和直接方式,但仍然没有进展。
这是代码
models.py
class Profile(models.Model):
user = models.OneToOneField(UserProfile, on_delete=models.CASCADE)
image = models.ImageField(upload_to='profile_images', null=True)
def __str__(self):
return self.user.name
HTML代码
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit" name="upload-profile-photo">Upload</button>
</form>
Views.py
if 'upload-profile-photo' in request.POST:
profile_instance = Profile.objects.get(user=token.user.id)
profile_instance.image = request.FILES["myfile"]
profile_instance.save()
return HttpResponse("Success")
请求信息
GET: No Get Data
POST: csrfmiddlewaretoken: .....
myfile: 'maxresdefault.jpg'
upload-profile-photo: ''
FILES: No FILES data
追踪
Traceback (most recent call last):
File "/home/piyush/PycharmProjects/doel/doel/venv_doel/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/home/piyush/PycharmProjects/doel/doel/venv_doel/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/piyush/PycharmProjects/doel/doel/venv_doel/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/piyush/PycharmProjects/doel/doel/venv_doel/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/piyush/PycharmProjects/doel/doel/venv_doel/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/home/piyush/PycharmProjects/doel/doel/venv_doel/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/home/piyush/PycharmProjects/doel/doel/venv_doel/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/piyush/PycharmProjects/doel/doel/venv_doel/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/home/piyush/PycharmProjects/doel/doel/doel_registration_api/views.py", line 933, in post
profile_instance.image = request.FILES["myfile"]
File "/home/piyush/PycharmProjects/doel/doel/venv_doel/lib/python3.6/site-packages/django/utils/datastructures.py", line 79, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'myfile'
答案 0 :(得分:1)
我有同样的错误。我发现问题出在我的 HTML代码上。这里有一些建议,看看是否可行-
检查您的<form>
代码。
尝试添加<input type="submit">
而不是<button>
查看向表单标签添加action
属性是否有帮助。
答案 1 :(得分:0)
我也面临着同样的问题,然后我发现了错误。 该错误不是在视图文件或模型文件中,而是在HTML代码中。
enctype="multipart/form-data"
在<form>
标记内请确保将其添加。