I am new to django and am having an issue with images. When i stay when I view the main page of my blog with all the articles everything is fine with the images, but as soon as I want to view one specific article, then the problems with the images start due to the wrong url/
urls.py (project)
from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py
from django.shortcuts import render
from .models import *
def index(request):
posts = Post.objects.all()
topics = Topic.objects.all()
return render(request, "index.html", {"posts": posts, "topics": topics})
def post(request, postinf):
post = Post.objects.get(title=postinf)
return render(request, "post.html", {"post": post} )
urls.py (app)
from django.urls import path
from . import views
urlpatterns = [
path('blog', views.index),
path('blog/<str:postinf>/', views.post, name="postdetail"),
]
settings.py
STATICFILES_DIRS = [
BASE_DIR / "main/static/",
]
STATIC_URL = 'main/static/'
models.py
from django.db import models
from django.contrib.auth.models import User
class Topic(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
user_avatar = models.ImageField(null=True, blank=True, upload_to="main/static/images")
def __str__(self):
return str(self.user)
class Post(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=20, verbose_name="Название поста")
post_text = models.TextField(max_length=500)
topic = models.ForeignKey(Topic, on_delete = models.DO_NOTHING)
time = models.DateField(auto_now=True)
post_image = models.ImageField(null=True, blank=True, upload_to="main/static/images")
def __str__(self):
return self.title
+no problem on the main page (http://127.0.0.1:8000/blog) with images
- when i go to http://127.0.0.1:8000/blog/post/ get this error on console and no images
Not Found: /blog/post/main/static/images/istockphoto-10252.jpg
[19/Apr/2023 01:28:00] "GET /blog/post/main/static/images/istockphoto-10252.jpg HTTP/1.1" 404 2699