Django REST Framework 图片上传
Django REST Framework image upload
我有型号产品:
def productFile(instance, filename):
return '/'.join( ['products', str(instance.id), filename] )
class Product(models.Model):
...
image = models.ImageField(
upload_to=productFile,
max_length=254, blank=True, null=True
)
...
然后我有序列化器:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = (
...
'image',
...
)
然后我有意见:
class ProductViewSet(BaseViewSet, viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
如何使用 Postman 上传图片?将图像上传到模型的最佳做法是什么?谢谢。
你可以创建单独的端点来上传图片,就像这样:
class ProductViewSet(BaseViewSet, viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
@detail_route(methods=['post'])
def upload_docs(request):
try:
file = request.data['file']
except KeyError:
raise ParseError('Request has no resource file attached')
product = Product.objects.create(image=file, ....)
你可以解决这个问题
-- 更新:
这是从邮递员上传的方法
我最近启动了 Django 并且在上传图片时遇到了同样的问题。
我完成的所有步骤
安装 Pillow 以使用 ImageField
pip install Pillow
在Settings.py
中添加这些行
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/' # 'http://myhost:port/media/'
使用 model.py 中的 ImageField(创建 nameFile
函数以创建文件夹和文件名)
def nameFile(instance, filename):
return '/'.join(['images', str(instance.name), filename])
class UploadImageTest(models.Model):
name = models.CharField(max_length=100)
image = models.ImageField(upload_to=nameFile, blank=True, null=True)
serializer.py
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = UploadImageTest
fields = ('name', 'image')
views.py
class ImageViewSet(ListAPIView):
queryset = UploadImageTest.objects.all()
serializer_class = ImageSerializer
def post(self, request, *args, **kwargs):
file = request.data['file']
image = UploadImageTest.objects.create(image=file)
return HttpResponse(json.dumps({'message': "Uploaded"}), status=200)
urls.py: 添加这一行
path('upload/', views.ImageViewSet.as_view(), name='upload'),
admin.py:添加这一行(用于管理员检查)
admin.site.register(UploadImageTest)
在终端
python manage.py makemigrations
python manage.py migrate
models.py
from django.db import models
class ImageUpload(models.Model):
title = models.CharField(max_length=50)
images = models.ImageField('images')
serializers.py
from rest_framework import serializers
from .models import ImageUpload
class ImageUploadSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ImageUpload
fields= (
'title',
'images'
)
views.py
from rest_framework import viewsets
from .models import ImageUpload
from .serializers import ImageUploadSerializer
class ImageUploadViewSet(viewsets.ModelViewSet):
queryset = ImageUpload.objects.all()
serializer_class = ImageUploadSerializer
urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'imageupload', views.ImageUploadViewSet)
urlpatterns = [
path('imageupload', include(router.urls)),
]
这对我有用
class UserAvatarUpload(ListAPIView):
parser_classes = [MultiPartParser, FormParser]
serializer_class = ImageSerializer
def post(self, request, *args, **kwargs):
username = request.data['username']
file = request.data['image']
user = MyModel.objects.get(username=username)
user.image = file
user.save()
return Response("Image updated!", status=status.HTTP_200_OK)
我有型号产品:
def productFile(instance, filename):
return '/'.join( ['products', str(instance.id), filename] )
class Product(models.Model):
...
image = models.ImageField(
upload_to=productFile,
max_length=254, blank=True, null=True
)
...
然后我有序列化器:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = (
...
'image',
...
)
然后我有意见:
class ProductViewSet(BaseViewSet, viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
如何使用 Postman 上传图片?将图像上传到模型的最佳做法是什么?谢谢。
你可以创建单独的端点来上传图片,就像这样:
class ProductViewSet(BaseViewSet, viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
@detail_route(methods=['post'])
def upload_docs(request):
try:
file = request.data['file']
except KeyError:
raise ParseError('Request has no resource file attached')
product = Product.objects.create(image=file, ....)
你可以解决这个问题
-- 更新:
这是从邮递员上传的方法
我最近启动了 Django 并且在上传图片时遇到了同样的问题。
我完成的所有步骤
安装 Pillow 以使用 ImageField
pip install Pillow
在
Settings.py
中添加这些行MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # 'http://myhost:port/media/'
使用 model.py 中的 ImageField(创建
nameFile
函数以创建文件夹和文件名)def nameFile(instance, filename): return '/'.join(['images', str(instance.name), filename]) class UploadImageTest(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to=nameFile, blank=True, null=True)
serializer.py
class ImageSerializer(serializers.ModelSerializer): class Meta: model = UploadImageTest fields = ('name', 'image')
views.py
class ImageViewSet(ListAPIView): queryset = UploadImageTest.objects.all() serializer_class = ImageSerializer def post(self, request, *args, **kwargs): file = request.data['file'] image = UploadImageTest.objects.create(image=file) return HttpResponse(json.dumps({'message': "Uploaded"}), status=200)
urls.py: 添加这一行
path('upload/', views.ImageViewSet.as_view(), name='upload'),
admin.py:添加这一行(用于管理员检查)
admin.site.register(UploadImageTest)
在终端
python manage.py makemigrations python manage.py migrate
models.py
from django.db import models
class ImageUpload(models.Model):
title = models.CharField(max_length=50)
images = models.ImageField('images')
serializers.py
from rest_framework import serializers
from .models import ImageUpload
class ImageUploadSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ImageUpload
fields= (
'title',
'images'
)
views.py
from rest_framework import viewsets
from .models import ImageUpload
from .serializers import ImageUploadSerializer
class ImageUploadViewSet(viewsets.ModelViewSet):
queryset = ImageUpload.objects.all()
serializer_class = ImageUploadSerializer
urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'imageupload', views.ImageUploadViewSet)
urlpatterns = [
path('imageupload', include(router.urls)),
]
这对我有用
class UserAvatarUpload(ListAPIView):
parser_classes = [MultiPartParser, FormParser]
serializer_class = ImageSerializer
def post(self, request, *args, **kwargs):
username = request.data['username']
file = request.data['image']
user = MyModel.objects.get(username=username)
user.image = file
user.save()
return Response("Image updated!", status=status.HTTP_200_OK)