0

Django

There are 2 question about this topic, but both of them (this is one Absolute paths on images uploaded by django-ckeditor) are not updated. For example, in Django 4.X, url was removed. Despite this, I've tried these solutions, but no one worked for me.

I've also tried to use:

CKEDITOR_MEDIA_PREFIX on my settings.py

But it didn't work either. This is my settings.py

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
CKEDITOR_UPLOAD_PATH = 'uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

This is my urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/news/', include('news.urls')),
    re_path(r'^ckeditor/', include('ckeditor_uploader.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += [
        re_path(r'^media/(?P<path>.*)$', serve, {
            'document_root': settings.MEDIA_ROOT
        }),
]

So here is my question, how can I set up my Django-rest-framework app in such way that I get the absolute path when I render the html on my next.js site?

This is what I get right now:

<img alt=\"\" src=\"/media/uploads/2022/01/19/video.svg\"/>

This is what I'd like to get:

<img alt=\"\" src=\"http://website.com/media/uploads/2022/01/19/video.svg\"

React
Is there any way to achieve these from the frontend? For example, updating all img's src

VicenteC
  • 311
  • 7
  • 26

1 Answers1

0

If you need a quick solution (I'm pretty sure this is not the "right" way of doing this), here is my approach:

As I only need to update the img.src in one JavaScript file, I did it using a hook to get all the images, filter only those ones that are stored in the server and update their src.

 useEffect(()=>{
        
        //! Don“t forget to update this
        const imgDomain = 'https://...'; 

        const imgStore = document.querySelectorAll("img[src]");
        Object.keys(imgStore).map((x)=>{

            if(imgStore[x].src.includes('uploads')){
                const originalURL = imgStore[x].src;
               var mediaPos =  originalURL.indexOf('/media/');
               var URLlength = originalURL.length;
               var slicedSRC = originalURL.slice (mediaPos, URLlength);
               var newSRC = imgDomain+slicedSRC;
               imgStore[x].src = newSRC;

            }
        })
        
    }, []); 
VicenteC
  • 311
  • 7
  • 26