This has been a nightmare for me. Many tutorials on how to upload multiple images to Django but I cannot find one that shows you how to add multiple images to a model with a foreign key to a post. Please tell me what I am doing wrong.
Post model:
from django.db import models
from django_extensions.db.fields import AutoSlugField
from django.contrib.auth import get_user_model
User = get_user_model()
class Post(models.Model):
name = models.CharField(max_length=150, verbose_name="event name")
category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1)
slug = AutoSlugField(populate_from=["category", "created_at", "user"])
body = models.TextField("content", blank=True, null=True, max_length=5000)
user = models.ForeignKey(
User, on_delete=models.CASCADE, verbose_name="author", related_name="posts"
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "post"
verbose_name_plural = "posts"
db_table = "posts"
ordering = ["created_at"]
def __str__(self):
return self.body[0:30]
def get_absolute_url(self):
return self.slug
Post image model:
class PostImage(models.Model):
image = models.FileField(upload_to=user_directory_path)
post = models.ForeignKey(Post, on_delete=models.DO_NOTHING)
class Meta:
db_table = "post_images"
ordering = ["post"]
Post serializer:
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = [
"category",
"body",
"video",
"can_view",
"can_comment",
"user",
"published",
"pinned",
"created_at",
"updated_at",
]
Image serializer:
class PostImageSerializer(serializers.ModelSerializer):
class Meta:
model = PostImage
fields = [
'image',
'post'
]
the view to create the post:
class PostCreate(APIView):
def post(self, request, format=None):
image_serializer = PostImageSerializer(data=request.FILES)
if(image_serializer.is_valid()):
for image in image_serializer:
PostImage.objects.create(image=image, post=self)
serializer = PostSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=HTTP_201_CREATED)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
I use Vue as the front end and the data sent to the backend is fine and it shows the images with the encoding and the fields.
How do I save the image and attach it to the post using the post ID
Please help