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

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}}

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})

How to upload Image Files on Shared Host/ Shared Folder using Django, Python?

I have two application server 10.1.xx.xx and 10.1.xx.yy and middle of both I have load balancer 10.5.aa.bb and I have deployed my Django application in both the servers successfully and able to access the application too.
There is a shared folder in between both the servers where I have to upload the images so that both servers have access of all the images, but I don't have any idea, how should I do it? up-till now I just upload the images in project folder. I googled a lot I just got this blog,
http://www.bogotobogo.com/python/Django/Python_Django_Image_Files_Uploading_On_Shared_Host_Example.php
but It is also not working.
I tried with following setting but it is uploading file in project directory.
settings.py
MEDIA_URL = '/home/bynry-01/www/media/'
MEDIA_ROOT='http://192.168.1.109:3333/www/media/'
model.py
class Document(models.Model):
description = models.CharField(max_length=255, blank=True)
document = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField(auto_now_add=True)
views.py
document=Document()
document.document = request.FILES['imgfile']
document.save()

Image not uploading on server while it is working well in localhost

I am trying to save an image to a folder when a user uploads the image and submits the signup form.
In models.py
image = models.ImageField(upload_to=upload_location, null=True, blank=True)
I have used a function upload_location to upload the images, here it is
def upload_location(instance, filename):
UserModel = instance.__class__
new_id = UserModel.objects.order_by("id").last().id + 1
return "user/%s/%s" %(new_id,filename)
It is working perfectly in localhost, but it is not even hitting function upload_location when i push the code to server. What am i doing wrong?
EDIT :
Came to know the actual problem. File size of more than 15kb is not uploading on server. Is this the django issue or server issue?

Django not uploading image files to Azure storage container

How do I link my Azure blob storage to my Django admin, such that it uploads the file to the blob storage account when saving a new record.
I have my image upload set up in the admin already. The admin interface acts like the image is attached before I click save, although I am aware that the image file is not actually stored in my SQLite3 database.
I can reference them successfully in the consumer-facing portion of my project when the images are manually uploaded to the Azure blob storage account. I don't want to manually upload them each time, for obvious reasons.
There has to be a simple solution for this, I just haven't had success in researching it. Thanks in advance!
models.py
class Image(models.Model):
file = models.ImageField(upload_to='img/')
def __unicode__(self):
return u'%s' % self.file
class Product(models.Model):
...
picture = models.ManyToManyField(Image)
...
settings.py
MEDIA_ROOT = path.join(PROJECT_ROOT, 'media').replace('\\', '/')
MEDIA_URL = 'https://my_site.blob.core.windows.net/'
Using Django 1.7, Python 2.7, SQLite3
Django-storages has support for an Azure blob backend which would allow any uploads you do to be automatically stored in your storage container.
http://django-storages.readthedocs.org/en/latest/backends/azure.html
I'm not aware of any built-in Django API that allows us to change the blob's content type. But from my experience, you can use Azure SDK for Python to upload blobs: https://github.com/Azure/azure-sdk-for-python. The most important setting in your case is the content type. By default content type is application/octet-stream. However you can change it via x_ms_blob_content_type. Please refer to https://azure.microsoft.com/en-us/documentation/articles/storage-python-how-to-use-blob-storage/ for a sample and feel free to let us know if you have any further concerns.
My Configuration
# Media
MEDIA_ROOT = '/home/<user>/media/'
MEDIA_URL = '/media/'
Remember folder need permission (write, read) apache user
example:
<img src="/media/img/my_image.png">
or
<img src="{{obj.file.url}}">

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='')

Categories

Resources