add image upload for Forum

parent ddcac344
......@@ -4,4 +4,4 @@ from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['post_title', 'post_body', 'author']
\ No newline at end of file
fields = ['post_title', 'post_body', 'author', 'image']
\ No newline at end of file
# Generated by Django 3.2.12 on 2022-05-18 16:13
import Forum.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Forum', '0002_auto_20220325_0135'),
]
operations = [
migrations.AddField(
model_name='post',
name='image',
field=models.ImageField(blank=True, null=True, upload_to=Forum.models.filepath),
),
]
from django.db import models
from Homepage.models import WidgetUser
from datetime import datetime
import os
def filepath(request, filename):
old_filename = filename
time_now = datetime.now().strftime("%Y%m%d%H:%M:%S")
filename = f"{time_now} {old_filename}"
return os.path.join("uploads/", filename)
# Create your models here.
class Post(models.Model):
post_title = models.CharField(max_length=50)
......@@ -9,6 +18,8 @@ class Post(models.Model):
author = models.ForeignKey(WidgetUser, on_delete=models.CASCADE, default=1)
image = models.ImageField(upload_to=filepath, null=True, blank=True)
def __str__(self):
return self.post_title
......
......@@ -19,7 +19,6 @@ body {
}
#thumbnail {
width: 150px;
height: 150px;
object-fit: cover;
object-position: center;
......
......@@ -23,7 +23,7 @@
<h1>New Forum Post</h1>
<form action="/posts/add/" method="post">
<form action="/posts/add/" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" id="save-post-btn" value="Save Post">
......
......@@ -23,7 +23,11 @@
<a href="/forum">Back to all posts</a>
</div>
{% if post.image %}
<img id="thumbnail" src="{{ MEDIA_DIR }}/uploads/{{ post.image }}" alt="thumbnail" />
{% else %}
<img id="thumbnail" src="{% static 'Forum/thumbnail.jpg' %}" alt="placeholder image" />
{% endif %}
<h1 id="title">{{ post.post_title }}</h1>
<h4 id="subtitle">by {{ post.author.first_name }} {{ post.author.last_name }}, {{ post.pub_date|date:"d/m/Y" }}</h4>
<p class="body-text">{{ post.post_body }}</p>
......
......@@ -22,7 +22,7 @@ class AddForumPostView(View):
return render(request, 'Forum/add.html', {'form': PostForm()})
def post(self, request):
form = PostForm(request.POST)
form = PostForm(request.POST, request.FILES)
if form.is_valid():
new_post = form.save()
return redirect('/forum')
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment