Today I tried to have images in my project and the idea is simple - create news with an image, title, and description. I wonder why when I set up my media files So I make my news in this view:
class NewsCreate(views.CreateView):
template_name = 'web/create_news.html'
model = News
fields = ('title', 'image', 'description')
success_url = reverse_lazy('home')
Here is the model:
class News(models.Model):
TITLE_MAX_LENGTH = 30
title = models.CharField(
max_length=TITLE_MAX_LENGTH
)
image = models.ImageField(
upload_to='news/',
blank=True
)
description = models.TextField()
Here is the set-up in settings.py:
MEDIA_ROOT = BASE_DIR / 'mediafiles'
MEDIA_URL = '/media/'
Here is the urls.py file:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('University_Faculty.web.urls')),
]
if settings.DEBUG:
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I've noticed that when I try to go to none existing URL this happens : wrong ulr page showing media as a correct one
This is the result in my media folder after 10 POST requests it shows in the database that it is actually creating the news, but the images won't go anywhere: no files media folder
CodePudding user response:
You need to correct
MEDIA_ROOT = BASE_DIR / 'media'
Hope this will work for you.
CodePudding user response:
add this to settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')