Django - How to save files to STATIC_ROOT from views? - python

I have made a Django app that takes arguments from the form and makes an image using Pillow.
views.py:
file_name = "{}.png".format(random.randint(1, 255))
image1.save(file_name)
pretty simple stuff, right? Now when I try to render that image with HttpResponse as:
return HttpResponse("<img src='" +file_name + "' alt='image here'>")
apparently, it will throw an error. Can you please tell me what to do in order to save it properly and show in HttpResponse?
Django==1.11.8
Pillow==5.0.0
Python 3.6.2
Thank you!

Firstly, you should be saving to MEDIA_ROOT. Secondly, you need to put an actual URL - ie relative to MEDIA_URL - in your img src, not just a filename. Third, you need to have something serving files at that URL.

Related

How to access media files uploaded via a Django form?

I am accepting an image from the user in a form in Django. How do I access the uploaded image to show it in the web browser?
This is what I have in settings.py
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
This is in my models.py
class Hotel(models.Model):
name = models.CharField(max_length=50)
image = models.ImageField(upload_to="images/")
Also, I have added the
if settings.DEBUG:
urlpatterns +=static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
in urls.py
I tried to access the image as
def image_view(request):
if request.method=='POST':
farm = hotelForm();
form = hotelForm(request.POST,request.FILES)
if form.is_valid():
form.save()
modelff = Hotel(name=request.POST['name'],image = request.FILES['image'])
# print(modelff.image.url)
return render(request,'djangoform.html',{"form":farm,"uploaded_data_url":modelff.image.url})
else:
form = hotelForm()
return render(request,'djangoform.html',{"form":form})
And in my template, I accessed the image as <img src="{{uploaded_data_url}}">. But the image does not show up and the console shows image not found.
P.S. I have seen How to access media files in django How to access uploaded files in Django?
https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development
Django : accessing uploaded picture from ImageField
But none of them seem to help me. I can't find how do I include the 'images/' in my path. My uploaded_data_url shows /media/Screenshot%202020-04-18%20at%206.39.24%20PM.png while I expect it to show /media/images/Screenshot%202020-04-18%20at%206.39.24%20PM.png
Where is the problem?
Also, if there can be something similar to How can I get uploaded text file in view through Django? (f.read() in this question) It would be great.
Edit: Since from an answer, it seems the question was not clear, I would like to clarify that the above was just what I tried and I don't really know if it is correct or not. Secondly, the whole purpose of doing this was to get image from user, process it, and display the original and final image to the user. So if there is any other method that you have to do this, please share that.
If the uploaded_data_url shows this /media/Screenshot%202020-04-18%20at%206.39.24%20PM.png then this means that the images were saved under the media dir. This is expected since your conf is MEDIA_URL = '/media/'.
If you want it as /media/images/Screenshot%202020-04-18%20at%206.39.24%20PM.png then change to this MEDIA_URL = '/media/images/'.
The problem with the above is that it will interfere with all other media files, so a simpler solution would be to replace the /media/ with /media/images/.
Adapt this in your views.py
url = str(modelff.image.url)
modUrl = url.replace("/media/","/media/images/")
return render(request,'djangoform.html',{"form":farm,"uploaded_data_url":modUrl l})

Best way to retrieve the url of a imageField in django

I'm using the following models:
class Product(models.Model):
# some other stuff
pictures = models.ManyToManyField(Image)
class Image(models.Model):
# MEDIA_ROOT = /full/path/to/my/media/folder/
image = models.ImageField(upload_to=settings.MEDIA_ROOT, default=DEFAULT_PROFILE_PICTURE)
Then in a view I wan to retrieve the images so i run the following code:
for pic in product.pictures.all():
pictures += [pic.image.url.replace(settings.PROJECT_ROOT, url)]
The problem here is that pic.image.url is giving me the system path, and I was expecting the relative path (something like /media/mypicture.jpg) so to fix this I used the replace function, but it looks to me that it should be a better way.
How can I build the model or access the image to avoid using the replace method?
Thanks in advance
You shouldn't use MEDIA_ROOT as a upload_to value. If you want to upload to MEDIA_ROOT without any subdirctories then just use an empty string '':
image = models.ImageField(upload_to='')

how to render django template from code instead of file on Google App Engine

I am writing a Google App Engine webapp that renders some html to a Django template. I want to either render the template using either a file or just some json thats very similar to that in file. Is it possible to use Django to render this to a file that is read in and stored in database?
The oldAPI.HTML is just an old version of api.html but with some small changes. Rendering Django to the api-html file works fine.
I understand that you can't store files on GAE, how can i dynamically use Django to render to HTML stored in memory?
path = ""
oldAPI = APIVersion().get_by_key_name(version)
if oldAPI is None:
path = os.path.join(os.path.dirname(__file__), "api.html")
template_values = {
'responseDict': responseDict,
}
if path:
self.response.out.write(template.render(path, template_values))
else:
self.response.out.write(template.render(oldAPI.html,template_values))
In order to render a template 'in memory', there are a few things you'll need to do:
App Engine Setup
First of all, you'll need to ensure that everything is set up correctly for Django. There's a lot of information on the Third-party libraries page, but I'll include it here for your benefit.
In main.py, or (whatever your script handler is), you'll need to add the following lines:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.2') # Change to a different version as you like
Don't forget to include django in your app.yaml:
libraries:
- name: django
version: "1.2"
Code Setup
Second of all, you'll need to create a Template object, as denoted in the Google App Engine template documentation. For example:
from google.appengine.ext.webapp import template
# Your code...
template_string = "Hello World"
my_template = template.Template(template_string)
# `context` is optional, but will be useful!
# `context` is what will contain any variables, etc. you use in the template
rendered_output = template.render(context)
# Now, do what you like with `rendered_output`!
You can instantiate a template from text in Django with just template.Template(my_text).
Unfortunately, there's no (builtin) way to do so, but you can get inspired from the function google.appengine.ext.webapp.template._load_user_django (GAE with Python 2.5) or google.appengine.ext.webapp.template._load_internal_django (GAE with Python 2.7) and write your very own wrapper overriding settings and rendering like GAE source does.

How do I properly display user-generated images using django?

I am trying to upload a user-generated image and then display in on my django web app. The image is getting uploaded to the server but I am having trouble displaying it.
models.py
image = models.ImageField(blank=True, null=True, max_length=255, upload_to="images/")
settings.py
MEDIA_ROOT = '/home/user/webapps/static/'
MEDIA_URL = 'http://user.webfactional.com/static/'
As an example, say I upload I file named Finland.gif. I can see the file uploaded. However when I look at the source, I see the source of the image as "www.foo.com/accounts/profile/images/Finland.gif" and not the static image url which should be "http://user.webfactional.com/static/images/Finland.gif". Any advice on how I should fix this?
userprofile.image.url gives you the full url to the image
Just solved it... I need to include:
http://user.webfactional.com/static/{{userprofile.image}}

How to delete old image when update ImageField?

I'm using Django to create a stock photo site, I have an ImageField in my model, the problem is that when the user updates the image field, the original image file isn't deleted from the hard disk.
How can I delete the old images after an update?
Use django-cleanup
pip install django-cleanup
settings.py
INSTALLED_APPS = (
...
'django_cleanup.apps.CleanupConfig', # should be placed after your apps
)
You'll have to delete the old image manually.
The absolute path to the image is stored in your_image_field.path. So you'd do something like:
os.remove(your_image_field.path)
But, as a convenience, you can use the associated FieldFile object, which gives easy access to the underlying file, as well as providing a few convenience methods. See http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield-and-fieldfile
Use this custom save method in your model:
def save(self, *args, **kwargs):
try:
this = MyModelName.objects.get(id=self.id)
if this.MyImageFieldName != self.MyImageFieldName:
this.MyImageFieldName.delete()
except: pass
super(MyModelName, self).save(*args, **kwargs)
It works for me on my site. This problem was bothering me as well and I didn't want to make a cleanup script instead over good bookkeeping in the first place. Let me know if there are any problems with it.
Before updating the model instance, you can use the delete method of FileField object. For example, if the FileField or ImageField is named as photo and your model instance is profile, then the following will remove the file from disk
profile.photo.delete(False)
For more clarification, here is the django doc
https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.fields.files.FieldFile.delete
You can define pre_save reciever in models:
#receiver(models.signals.pre_save, sender=UserAccount)
def delete_file_on_change_extension(sender, instance, **kwargs):
if instance.pk:
try:
old_avatar = UserAccount.objects.get(pk=instance.pk).avatar
except UserAccount.DoesNotExist:
return
else:
new_avatar = instance.avatar
if old_avatar and old_avatar.url != new_avatar.url:
old_avatar.delete(save=False)
My avatrs has unique url for each person like "avatars/ceb47779-8833-4719-8711-6f4e5cabb2b2.png". If user upload new image with different extension like jpg, delete_file_on_change_extension reciever remove old image, before save new with url "avatars/ceb47779-8833-4719-8711-6f4e5cabb2b2.jpg" (in this case). If user uploads new image with same extension django overwrite old image on storage (disk), because images paths are the same.
This works fine with AWS S3 django-storage.
Here is an app that deletes orphan files by default: django-smartfields.
It will remove files whenever:
field value was replaced with a new one (either uploaded or set manually)
field is cleared through the form (in case that field is not required, of course)
the model instance itself containing the field is deleted.
It is possible to turn that cleanup feature off using an argument: ImageField(keep_orphans=True) on per field basis, or globally in settings SMARTFIELDS_KEEP_ORPHANS = True.
from django.db import models
from smartfields import fields
class MyModel(models.Model):
image = fields.ImageField()
document = fields.FileField()
try this, it will work even if old file is deleted
def logo_file(instance, filename):
try:
this = business.objects.get(id=instance.id)
if this.logo is not None:
path = "%s" % (this.logo)
os.remove(path)
finally:
pass..
code will work even without "try .. finally" but it will generate problem if file was accidently deleted.
changed: move model matching inside "try" so it will not throw any error at user signup
Let me know if there are any problems.
Completing Chris Lawlor's answer, tried this and works.
from YOURAPP.settings import BASE_DIR
try:
os.remove(BASE_DIR + user.userprofile.avatarURL)
except Exception as e:
pass
The URL has a pattern of /media/mypicture.jpg
What I did is saving the path to the old image and if form is valid I would delete the old one.
if request.method == 'POST':
old_image = ""
if request.user.profile.profile_picture:
old_image = request.user.profile.profile_picture.path
form = UpdateProfileForm(request.POST,request.FILES,instance = profile)
if form.is_valid():
if os.path.exists(old_image):
os.remove(old_image)
form.save()
It is a little messy , but you do not install third parties or anythin

Categories

Resources