2

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

4
  • Write FileField in place of ImageField, and it's recommended to make the folder media instead of mediafiles. Commented Mar 25, 2022 at 18:06
  • potential duplicate or similar here: stackoverflow.com/questions/32423123/… Commented Mar 25, 2022 at 18:13
  • @Sunderam tried that, but still same result Commented Mar 25, 2022 at 21:12
  • Problem found I haven't put enctype="multipart/form-data" in form tag I should've put the template in the question aswell Commented Mar 25, 2022 at 21:26

2 Answers 2

1

add this to settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Sign up to request clarification or add additional context in comments.

2 Comments

That is basically(BASE_DIR)already maintained above in settings.py,by importing os and resolving parent.parent, consequently doing the same.
see here could be a permission issue if code is correct : stackoverflow.com/a/73045506/3904109
0

You need to correct

MEDIA_ROOT = BASE_DIR / 'media'

Hope this will work for you.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.