I am trying to add images to a post. (Using Django v3.2.5)
root_directory/settings.py:
BASE_DIR = Path(__file__).resolve().parent.parent
...
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
root_directory/urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('index.urls')),
path('app2/', include('app2.urls')),
path('app3/', include('app3.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
app3/models.py:
from django.db import models
from ckeditor.fields import RichTextField
class Post_Picture(models.Model):
title = models.CharField('Title', max_length=120)
image = models.ImageField(blank=True, null=True, upload_to="images/")
caption = RichTextField(blank=True, null=True)
def __str__(self):
return self.title
app3/forms.py:
from django import forms
from django.forms import ModelForm
from .models import Post_Picture
class PostPicForm(ModelForm):
class Meta:
model = Post_Picture
fields = ('title', 'image', 'caption')
labels = {
'Title': '',
'Caption': '',
}
widgets = {
'title': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Title your post'}),
'caption': forms.Textarea(attrs={'class':'form-control', 'placeholder': 'Anything extra you want to add?'}),
}
app3/views.py:
from django.shortcuts import render, redirect
from .models import Post_Picture
from .forms import PostPicForm
from django.http import HttpResponseRedirect
from django.contrib import messages
def your_home(request):
friend_posts = Post_Picture.objects.all()
return render(request, "app3/your_home.html", {
'friend_posts': friend_posts,
})
def post_pic(request):
submitted = False
if request.method == "POST":
form = PostPicForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('post_pic?submitted=True')
else:
form = PostPicForm()
if 'submitted' in request.GET:
submitted = True
return render(request, 'app3/post_pic.html', {'form': form, 'submitted': submitted})
app3/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('your_home', views.your_home, name='your-home'),
path('post_pic', views.post_pic, name='post_pic'),
]
pip installed stuff:
$ pip freeze
asgiref==3.5.2
Django==3.2.5
django-ckeditor==5.9.0
django-js-asset==2.0.0
Pillow==9.3.0
pytz==2022.6
six==1.16.0
sqlparse==0.4.3
I did create the media folder but it didn't work - it didn't make the "image/" directory. During the submission process of posting pictures, it showed no error. I knew it wouldn't show the image on the website but, with that code, I'm pretty sure it should've shown the image in the admin area, but it didn't.
Any help is appreciated.