I have a blog that uses Django and currently I am building a page for creating new posts.
In my Post model I have a Foreign Key field that is linked to a ImageField. When rendering the page using a generic class view, the field is displayed as a drop-down as expected, but I would like to add new thumbnails, not only selecting the existing ones, similar to the behavior of the admin page when there is a Foreign Key field, where:
- There is a plus sign next to the drop-down
- When clicked, shows a pop up where I can upload the image
- After uploading the image, return to the main page, where the new option is created in the drop-down
How can I have a behavior similar to the admin's in my page? I tried to implement it as a widget, but the end result is very messy, as it just redirects to the admin page and I have to go back to my post creation page and reload to show the new option.
Alternatively I could just replace the the Foreign Key drop-down with a field to upload a file, but I don't know how, as the foreign key field expects an object not a file.
Here's my simplified models:
class Image(models.Model):
image = models.ImageField()
alt_tag = models.Charfield(max_length=30)
class Post(models.Model):
title = models.CharField(max_length=60)
content = models.TextField()
thumbnail = models.ForeignKey(Image, on_delete=models.SET_NULL)
When rendering a page for creating new posts, I am using a generic class view:
class PostCreateView(CreateView):
model = Post
template_name = '../templates/post_create_form.html'