使用request.data和request.FILES时发生KeyError吗?

时间:2018-09-12 07:09:48

标签: python django django-rest-framework

我想将图像上传到我的数据库。我可以使用ModelSerializer做到这一点。没问题,但是如果我想使用serializers.Serializer通过。
所以我的serializers.py看起来像这样:

class QuestionSerializer(serializers.Serializer):
    image = serializers.ImageField()
    name = serializers.CharField(max_length=120)

我的models.py看起来像这样:

class UploadedImage(models.Model):
    image = models.ImageField("Uploaded image", 
    upload_to=scramble_uploaded_filename)
    name = models.CharField(max_length=120)

and views.py:

class UploadedImagesViewSet(viewsets.ModelViewSet):
    queryset = UploadedImage.objects.all()
    serializer_class = QuestionSerializer

    def create(self,request):
        serializer1 = self.get_serializer(data=request.data)
        serializer.is_valid()
        data = serializer1.data
        print(data)
        img,iss = UploadedImage.objects.get_or_create(name=data['name'],defaults={'image':files['image']})
        return Response("UploadedImage")

在views.py中,当我执行data=request.data时会显示keyError in image,而当我执行data=request.FILES时则会显示shows KeyErrorIn name。如何解决此错误?如何上传图片并将名称保存在数据库中?

回溯:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/upload/

Django Version: 2.0.7
Python Version: 3.6.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'app1',
 'practice']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 '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 "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/query.py" in get_or_create
  487.             return self.get(**lookup), False

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/query.py" in get
  403.                 self.model._meta.object_name

During handling of the above exception (UploadedImage matching query does not exist.), another exception occurred:

File "/home/dinesh/.local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/home/dinesh/.local/lib/python3.6/site-packages/rest_framework/viewsets.py" in view
  103.             return self.dispatch(request, *args, **kwargs)

File "/home/dinesh/.local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  483.             response = self.handle_exception(exc)

File "/home/dinesh/.local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
  443.             self.raise_uncaught_exception(exc)

File "/home/dinesh/.local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  480.             response = handler(request, *args, **kwargs)

File "/media/dinesh/0A12B39C12B38B69/Drf_practice/ems/app1/views.py" in create
  31.       img,iss = UploadedImage.objects.get_or_create(name=data['name'],defaults={'image':data['image']})

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/query.py" in get_or_create
  489.             return self._create_object_from_params(lookup, params)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/query.py" in _create_object_from_params
  521.                 obj = self.create(**params)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/query.py" in create
  417.         obj.save(force_insert=True, using=self.db)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/base.py" in save
  729.                        force_update=force_update, update_fields=update_fields)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/base.py" in save_base
  759.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/base.py" in _save_table
  842.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/base.py" in _do_insert
  880.                                using=using, raw=raw)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/query.py" in _insert
  1125.         return query.get_compiler(using=using).execute_sql(return_id)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1284.             for sql, params in self.as_sql():

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in as_sql
  1237.                 for obj in self.query.objs

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in <listcomp>
  1237.                 for obj in self.query.objs

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in <listcomp>
  1236.                 [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in pre_save_val
  1186.         return field.pre_save(obj, add=True)

File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/fields/files.py" in pre_save
  285.         if file and not file._committed:

Exception Type: AttributeError at /upload/
Exception Value: 'list' object has no attribute '_committed'

1 个答案:

答案 0 :(得分:0)

验证后,您不想访问serializer1.data。 而是应通过serializer1.validated_data完成操作,然后您将在其中找到文件。