0

I'm facing an issue with serving my static files. My images are stored in project/static/images

When I try to display images on my homepage, no problem, the url is good. But now that I'm trying t o display images on other pages I have the following error :

"GET /contact_details/static/images/contact_image.png HTTP/1.1" 404 4212 Django is adding the name of my page 'contact_details' before the image path.

Here's my code :

settings.py

BASE_DIR = Path(__file__).resolve().parent.parent

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR,'accounts'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

STATIC_URL = '/static/'

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

MEDIA_URL = '/images/'

MEDIA_ROOT =BASE_DIR /'images'

urls.py

urlpatterns = [
    path('', views.home, name="home"),
    path('contact_details/', views.contactDetails, name="contact_details"),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py

def contactDetails(request, pk):
    contact = Contact.objects.get(id=pk)
    image = Image.objects.get(id=contact.image_id)

    form = ContactForm(instance=contact)
    if request.method == 'POST':
        form = ContactForm(request.POST, request.FILES, instance=contact)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('contact_image', args=(pk,)))

    context = {'contact' : contact, 'image' : image, 'form' : form}

    return render(request, 'accounts/contact_details.html', context)

contact_details.html

{% load static %}

<img src="{{ image.path }}" class="img-fluid">

I found on the forum that for other people the problem came from the STATIC_URL not starting with a slash, but in my case in didn't change nothing.

EDIT

It works now with these 2 changes :

settings.py

STATIC_URL = '/static/'

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

MEDIA_URL = '/images/'

MEDIA_ROOT =BASE_DIR

contact_details.html

{% load static %}

<img src="{{ image.path.url }}" class="img-fluid">

Daze8
  • 1
  • 2

0 Answers0