Search code examples
djangopostimage-uploadingtemporary-files

How to add image into a post in django


I'm building an blog system, which allow user add image to their blog.

when user add image, the image will be upload automatically, this happened before the blog is posted, so how should I handle the uploaded image, these image is kind of like temporary image, because if the user post the blog, these images will have an foreign key to this blog , and saved into some folder,but if the user discard the blog , these temporary images should be deleted.

the problem is how to get the firstly uploaded images,when the blog is actually posted? where should I store these temporary images? and how can I tell if the user discard the blog?


Solution

  • I would suggest the following:

    1. Modify the Post model to add a datetime field called published which allows NULL.
    2. Use the field published to determine if the post is published yet or not. A post will be considered as a draft if the published field has NULL, published otherwise.
    3. Create the post as soon as you hit the create post button. This will give you a Post object with the id which you can bind to a ModelForm and display to the user for editing. So when they add a picture, you can upload it and bind it to the id of the post in whatever way you want.
    4. Change the published to the datetime.now() only when you hit the publish button.
    5. Deleting a published or draft post should delete all of the linked resources like images.

    Hope it helps.