How to delete existing image while uploading new image in django - python

Let say I have a model which has a profile pic image field.As a user I uploaded a profile pic.When I upload a new profile pic, old profile has to get deleted.
How to handle this scenario in development and production stage

Use django-cleanup, it automatically deletes unnecessary files from server.
pip install django-cleanup
And add it to your settings.py:
INSTALLED_APPS = [
...
'django_cleanup'
]
Possible duplicate of:
https://stackoverflow.com/a/28986357/7320045

Related

Django upload and download files in google drive using googledriveapi

I am new to django and trying to create a web app to upload and download files to the google drive using gdriveapi.
I have gone through the python quickstart for Google drive and tried the code in manage.py where it is working.
How to write the same code to obtain credentials and upload and download in the django app?
How to write the view and model in django to obtain credentials and upload files to gdrive?
for my model field I use file = models.FileField(upload_to='todo', storage=gd_storage, blank=True, null=True), where todo is the app name. For the view I simply used the generic ModelViewSet, where you can just serializer.save(file=self.request.data['file'])

Cannot locate local path of uploaded file to Heroku from django using ephemeral file system( Web based Application)

I have recently deployed my first django project to Heroku. My project is a Web Based Application that allows users to upload a file to the server and the server will export a product after processing it.
The views.py processing the upload process is as follows
if form.is_valid():
task= form.save(commit=False)
task.task_created_by = request.user
task.save()
The model is as follows
class db(models.Model):
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
description = models.CharField(max_length=255, blank=True)
excel = models.FileField(upload_to='task/excel/')
userinput = models.FileField(upload_to='task/userinput/')
output= models.FileField(blank=True,null=True)
uploaded_at = models.DateTimeField(auto_now_add=True)
settings.py
#Media path setting
MEDIA_URL = '/uploaded/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded')
Therefore, a part of the server involves accessing the user uploaded file and thus processing it.
I did not set up any external file storage service(e.g. aws s3) and is only using the default ephemeral file system.
when I first run the application the server response this error
No such file or directory: '/app/uploaded/task\\excel\\abc.xlsx'
However, as I am using the django model file field, when I go to the django admin panel, it shows the file is uploaded and can be downloaded from the admin panel...
Therefore, the question is where did Heroku saved the uploaded file locally...
I have tried the heroku run bash method to search for the file but with no luck...
Any help would be appreciated, many thanks!!

django-tenants: access tenant media files in script

I am running an app built with djang-tenants. The app asks the user (tenant) to upload some data. I want the data to be segregated in sub directories for each tenant.
Acccording to the doc (https://django-tenants.readthedocs.io/en/latest/files.html), here is how media root is configured:
settings.py
MEDIA_ROOT = "/Users/murcielago/desktop/simulation_application/data"
MULTITENANT_RELATIVE_MEDIA_ROOT = "%s"
On the upload everything is great.
Now, I can't find a way to retrieve the file being uploaded within the app. Basically I need the app to serve the file corresponding to which tenant is requesting it.
Here is how I thought this would work:
from django.conf import settings
media_file_dir = settings.MULTITENANT_RELATIVE_MEDIA_ROOT
df = pd.read_csv(media_file_dir+'/uploads/sample_orders_data.csv')
but this does not work.
I have made it work so far grabbing the tenant name from the url and passing it to the app using pickle but this is not right in terms of security and won't scale.
Would someone has a clue on the best way to handle the lecture of tenant specific files?

Django Admin add support for HEIC for ImageField

please has someone experience with adding support of new image formats to the Django Admin module? I want to use this one called pyheif-pillow-opener pyheif-pillow-opener for HEIC support. It should be registered, but I am not sure where exactly. I tried to install that module and then in Django Admin upload an image to ImageField, but still, I am getting a message:
Upload a valid image. The file you uploaded was either not an image or a corrupted image.
EDIT - Solution:
There is only need to add to a used Django applications admin.py file these lines of code:
from pyheif_pillow_opener import register_heif_opener
register_heif_opener()
Another solution(add it to admin.py as TS suggest):
try:
from pillow_heif import HeifImagePlugin
except ImportError:
HeifImagePlugin = None # here you can log a warning

How to allow editing of templates for email by admin user in Django?

I need to allow the admin user to make an email template in html, and the user should be able to add dynamic variables where needed. The template will be saved in the database. For example,
Dear {{user.first_name}},
Thanks for participating in our cooking class on {{cooking_class.date}}
Then, there will be a cron job which will send emails and fill the dynamic variables.
What are my options? Is there a django package for this? I am using Django 1.4.3
thanks
I implemented something similar, here's what I did:
Create an app, and registered a model to store the email
Set up a management command to process the email
Manage the cron job via django-chronograph
Rendering the email, I used render_to_string, for example
from django.template.loader import render_to_string
from myproject.myemailapp.models import EmailTpl
email_tpl = EmailTpl.objects.get(...#criteria here)
# fetch the rest of your dynamic variables
rendered_tpl = render_to_string(email_tpl.user_entered_tpl, {
"user": user,
"cooking_class": cooking_class,
# ... and so on
})
Alternatively, Django Packages has some packages you might want to look into. Would be great if you post back the route you decided.
The plugin django-dbtemplates allows you to store templates in your database, and you can expose the dbtemplate app on your Admin site to edit. You can set your middleware settings such that either the database template or the same template in other locations has priority for loading.
We are using this in a project to manage templates for different products, with the database-stored template for each product linked by ForeignKey.

Categories