0

Trying to get image stored in django model in react js

Firstly I have upload image from react to django rest and saved it in a model.It saved like this "/media/project_mainimage/newimage.jpg".But now I want to get this image from django to react and display in tag but it doesn't load.

Settings.py

           MEDIA_URL='/media/'
           MEDIA_ROOT=os.path.join(BASE_DIR, 'media')

Models.py

       description=models.CharField(max_length=600,blank=True,null=True)
       main_image=models.ImageField(upload_to='project_mainimage')
       videourl=models.CharField(max_length=450,blank=True,null=True)

Urls.py

urlpatterns = [

url('admin/', admin.site.urls),
url(r'^portfolio/', include('PortfolioApp.urls')),

   ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

React Js component:

    <img  src={this.state.project.main_image} width="184" height="40" 
    alt="Project image"/>  // shows nothing
    <h1>{this.state.project.main_image}</h1> // shows "/media/project_mainimage/newimage.jpg"
Nabeel Ayub
  • 1,060
  • 3
  • 15
  • 35

1 Answers1

-3

"/media/project_mainimage/newimage.jpg" wont works . It should be a complete URL , for example "https://localhost/media/project_mainimage/newimage.jpg"

For this your server should return the complete url , otherwise you can pre-bind your server address with /media/project_mainimage/newimage.jpg.

  • 3
    No, URLs starting with a slash are perfectly fine. The browser will use the same protocol and server as the current page. –  Apr 23 '19 at 12:02