我尝试在rest_framework中上传图片。我无法修复此错误,因为我是新的rest_framework,有人可以解决此错误。
我的所有model.py,serializers.py,views.py和urls.py如下所示:
models.py
def scramble_uploaded_filename(instance, filename):
extension = filename.split(".")[-1]
return "{}.{}".format(uuid.uuid4(), extension)
class UploadedImage(models.Model):
image = models.ImageField("Uploaded image", upload_to=scramble_uploaded_filename)
name = models.CharField(max_length=120)
serializers.py
class QuestionSerializer(serializers.ModelSerializer):
image = serializers.ImageField()
name = serializers.CharField(max_length=120)
class Meta:
model = UploadedImage
fields = ('image','name')
views.py
class UploadedImagesViewSet(viewsets.ModelViewSet):
queryset = UploadedImage.objects.all()
serializer_class = QuestionSerializer
def create(self,request):
serializer1 = self.get_serializer(data={**request.data,**request.FILES})
serializer1.is_valid()
data = serializer1.data
print(data)
img,iss = UploadedImage.objects.get_or_create(name=data['name'],defaults={'image':data['image']})
return Response("UploadedImage")
urls.py
from django.urls import path,include
from rest_framework import routers
from app1 import views
router = routers.DefaultRouter()
router.register(r'',views.UploadedImagesViewSet)
urlpatterns = [
path('',include(router.urls)),
]
回溯:
Exception Value: 'list' object has no attribute 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/'_committed'
我的所有回溯都在这里。为什么会出现这种类型的错误? 请解决这个错误的人吗?