32π
β
you can create separate endpoint for uploading images, it would be like that:
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, ....)
you can go around that solution
π€Shehab ElDin
24π
I lately start Django and have same problem for upload image.
All steps that i done
-
Install Pillow for using ImageField
pip install Pillow
-
In
Settings.py
add these linesMEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # 'http://myhost:port/media/'
-
Use ImageField in model.py (create
nameFile
function for create folder and name of file)def upload_to(instance, filename): return '/'.join(['images', str(instance.name), filename]) class UploadImageTest(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to=upload_to, 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: add this line
path('upload/', views.ImageViewSet.as_view(), name='upload'),
-
admin.py: add this line (for check in admin)
admin.site.register(UploadImageTest)
-
in terminal
python manage.py makemigrations python manage.py migrate
π€Radesh
- [Django]-Is virtualenv recommended for django production server?
- [Django]-Unable to perform collectstatic
- [Django]-Apache or Nginx to serve Django applications?
4π
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)),
]
- [Django]-No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
- [Django]-Django : Testing if the page has redirected to the desired url
- [Django]-Can I make list_filter in django admin to only show referenced ForeignKeys?
1π
this worked for me
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)
π€Aditya Rajgor
- [Django]-Django "get() got an unexpected keyword argument 'pk'" error
- [Django]-Django Cache cache.set Not storing data
- [Django]-Login with code when using LiveServerTestCase with Django
Source:stackexchange.com