Django Rest Framework ImageField

后端 未结 5 1803
旧巷少年郎
旧巷少年郎 2020-12-07 18:54

I can not save the image in this ImageField.

when sending data back:

{
    \"image\": [\"No file was submitted. Check the encoding t         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 19:18

    **
    Django Rest Framework Image Upload
    views.py
        class FileUploadView(APIView):
        permission_classes = []
        parser_class = (FileUploadParser,)
    
        @csrf_exempt
        def uploatuserprofile( request):
    
            #fetches specific user image
            if request.method=='GET':
                user_data=JSONParser().parse(request)
                obj=UserProfile.objects.filter(user=user_data["user"])
                serializer=UserProfileSerializer(obj,many=True)
                return JsonResponse(serializer.data,safe=False)
    
    
    
            if request.method == 'POST':
                # print('=====================================================================================>',request.FILES['profile_image'])
                
                # print("##################################################################################### ",request.POST['user'])
                try:
                    s = UserProfile.objects.create(user_id = request.POST['user'], profile_image=request.FILES['profile_image'])
                    s.save()
                except:
                    return JsonResponse('Failed to upload Integrity error',safe=False)
    
                
    
                # file_serializer=UserProfileSerializer(request.POST,request.FILES)
            
                # if file_serializer.is_valid():
                #     file_serializer.save()
                return JsonResponse('profile uploded Sucessfully!!',safe=False)
            return JsonResponse('Failed to upload',safe=False)
    
    urls.py of application
    
     url(r'^uploatuserprofile/$',views.FileUploadView.uploatuserprofile),
    
    
    urls.py of project
    from django.conf import settings
    from django.conf.urls.static import static
    
    from django.contrib import admin
    from django.urls import path
    from django.conf.urls import url,include
    urlpatterns = [
        path('admin/', admin.site.urls),
        url(r'^',include('ChatApp.urls'))
    ]
    if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL,
                              document_root=settings.MEDIA_ROOT)
    
    models.py
    
    class UserProfile(models.Model):
        user = models.ForeignKey(Users,on_delete=models.CASCADE)
        profile_image = models.ImageField(upload_to='images/', blank=True, null=True)
    
    
    
        def __str__(self):
            return self.profile_image.name
    
    
    
    
    
    setting.py
    
    STATIC_URL = '/images/'
    STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "images"),
    
    ]
    STATIC_DIR = os.path.join(BASE_DIR, 'images')
    # Base url to serve media files
    MEDIA_URL = '/media/'
    
    # Path where media is stored
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')`enter code here`**
    

提交回复
热议问题