How to display uploaded Dicom image metadata in detailed view in Django? - python

I am a new to coding and working on a small Django project in which I want to display Dicom image metadata. I included FileField in the Django model to upload a Dicom image and I want to display the uploaded Dicom image metadata in Generic detailed view. I tried overriding the context method and accessing the image path but getting an error. How do I proceed with it? Please help!
#My model
class Patient(models.Model):
name = models.CharField(max_length=100)
ailment = models.TextField(max_length=200)
date_tested = models.DateTimeField(default=timezone.now)
image = models.ImageField(upload_to='.',default='download.jpg')
dicom = models.FileField(upload_to='dicom/',null=True)
#My Detailed view
class PatientDetailView(LoginRequiredMixin,DetailView):
model = Patient
def get_context_data(self,**kwargs):
medinfo = dict()
context = super().get_context_data(**kwargs)
dcpimg = imageio.imread(self.dicom.path)
for keys in dcpimg.meta:
medinfo[keys] = str(dcpimg.meta[keys])
context['medinfo'] = medinfo
return context
##Iam getting this error
AttributeError: 'PatientDetailView' object has no attribute 'dicom'

When you are calling self.dicom.path, self here refers to PatientDetailView class.
Try calling:
self.model.dicom.path

Related

Django do not update ImageField

Why Django update() do not update image file in media folder, but update everything else in update process.. Old image is in media folder, but there is no new image in folder.. When creating (using save()) everything is fine.. Any help, thanks in advance...
Here is the model class:
class Company(models.Model):
name = models.CharField(max_length=100)
companyAddress = models.CharField(max_length=70)
companyPhoneNumber = models.CharField(max_length=30)
companyDescription = models.CharField(max_length=150)
companyProfileImage = models.ImageField(upload_to='images/', default = "images/defaultCompany.jpg", null = True)
Here is the code that I use when update:
newName = request.data['name']
newAddress = request.data['address']
newPhoneNumber = request.data['phoneNumber']
newDescription = request.data['description']
newCompanyProfileImage = request.data['image']
Company.objects.filter(id = companyId).update(name = newName, companyAddress = newAddress,
companyPhoneNumber = newPhoneNumber, companyDescription = newDescription, companyProfileImage = newCompanyProfileImage)
The .update method bypasses the model's save method.
As noted in the docs:
The file is saved as part of saving the model in the database, so the actual file name used on disk cannot be relied on until after the model has been saved.
Because you are using .update, you are bypassing the save method and therefore the image is not saved to disk.
You must either (1) use .save to update the image OR (2) access the field storage class to 'manually' place the image in the correct location according to the configured storage backend (tricky, potentially unreliable so should be done in a transaction).
Since you're just updating one object, just using the .save method is probably the most straightforward solution:
obj = Company.objects.filter(id=companyId)
obj.name = newName
obj.companyAddress = newAddress
# ... etc
obj.companyProfileImage = newCompanyProfileImage
obj.save()

Save list of images from models django

I am using Django 3 and I want to create a Model where I upload a tensor file (called ct), then I elaborate it, extract the slices of this tensor and save the single slices as different images.
here is my model:
class Case(models.Model):
slug = ShortUUIDField(max_length=3)
title = models.CharField(max_length=50)
#...
ct = models.FileField()
# here I want to save a series of images that I extracted from the tensor 'ct'
'ct' is a 3D scan that I have to upload as a file
The number of images extracted is not constant.
I have a function called 'get_slices' that receives a ct and returns the images to be saved
Can you please help me step by step?
You can create another model and connect it to the original model (with ForeignKey).
Use ImageField if you just want to save the image
class Case(models.Model):
slug = ShortUUIDField(max_length=3)
title = models.CharField(max_length=50)
# Use ct = models.ImageField(title) if you want to save at least one photo'ct'
class Case_images(models.Model):
case = models.ForeignKey(Case, on_delete=models.CASCADE)
image = models.ImageField(upload_to=case.title)
Use these codes when you want to upload a ct:
def upload_a_ct(title, slug, ct):
c = Case(slug=slug, title=title)
c.save()
for image in get_slices(ct):
Case_images.objects.create(image=image, case=c)
The solution to the problem is here:
Automatically save list of images in ImageField after upload - django 3 <<<

Why does Django save pictures twice?

I am trying to overwrite the save function. What I want is to resize the original photos to a default size (800 * 534) and then to generate a thumbnails for this picture. However, I found the photos were stored twice.
For example, I add a photo named sample.jpg at first time. There are three photos in my directions. One is in ../Media/photos/ and the others are in ../Media/. When I save this picture again, there are four photos. Two are in ../Media/photos/, and the others are in ../Media/.
I am really confused why Django stores the picture twice and why my pictures were stored in ../Media not in ../Media/photos. What I want is to make only two pictures which the 800*534 picture and its thumbnail picture in ../Media/photos.
Here are my codes.
The class Photo:
class Photo(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250)
summary = models.TextField(blank=True)
created_date = models.DateField(auto_now_add=True)
modified_date = models.DateField(auto_now=True)
image = models.ImageField(upload_to='photo/')
album = models.ForeignKey(Album, on_delete=models.CASCADE)
is_cover_photo = models.BooleanField(default=False)
The save function I wrote in class Photo
def save(self):
if not self.pk:
filename = self.image
if filename:
print(filename)
img = Image.open(filename)
# save the default size photo
default_size = (800, 534)
img.thumbnail(default_size, Image.ANTIALIAS)
img.save(self.get_img_filename(filename))
# save thumbnail photo
cover_size = (342, 229)
img.thumbnail(cover_size, Image.ANTIALIAS)
img.save(self.get_img_thumb_filename(filename))
super(Photo, self).save()
And the other two functions:
def get_img_filename(self, img):
return img.path
def get_img_thumb_filename(self, img):
img_pre, img_ext = os.path.splitext(img.path)
thumb_name = img_pre + '_thumb' + img_ext
return thumb_name
This happens because your program is still calling the super class's save method which implicitly saves all the fields, including "image". Therefore, you have duplicated images in your server.
you can pass a parametter inside the save function like this:
img.save(self.get_img_filename(filename), save=False)
Your problem is that you are PIL.Image is saving the image localy plus in the Model Db you are calling it another save storing it localy like Lukas Herman said.
you need a way to store Image into ImageField possible without using PIL.Image.save(). here is a link I found : link-stackoverflow
Another Posible Solution is to store using Image Class and store the image and save the path location to CharField or TextField

django-stdimage dynamic file structure

I am using django-stdimage in a django web app. I want to upload images using in a dynamic file structure according to when the image was uploaded. For instance:
snapshot/<year>/<month>/<filename>
Therefore, if I uploaded an image in May 2013, the image should be placed in this directory:
snapshot/2013/05/
My code looks like this in my models.py:
class Snapshot(BaseModel):
...
image = StdImageField(upload_to='snapshot/%Y/%m', blank=False, size=(1170, 780), thumbnail_size=(100, 100, True))
...
In my template, I display the thumbnail like this:
<img src="{{snapshot.image.thumbnail.url}}">
We have since uploaded many images in the month of May. However, now that we have switched from May to June, all of the thumbnail paths are now pointing to June (current month) and not May (the month that we uploaded the images).
Does anyone know how I would fix this for future files uploaded and also files that were uploaded in the past?
We met the same bug.
Cause of this bug: every time this StdImage instance init its .thumbnail field, it calls self.generate_filename to get its filename, then insert an '.thumnail' into filename as name of thumbnail.
Source:
def _set_thumbnail(self, instance=None, **kwargs):
"""Creates a "thumbnail" object as attribute of the ImageField instance
Thumbnail attribute will be of the same class of original image, so
"path", "url"... properties can be used
"""
if getattr(instance, self.name):
filename = self.generate_filename(instance,
os.path.basename(getattr(instance, self.name).path))
thumbnail_filename = self._get_thumbnail_filename(filename)
thumbnail_field = ThumbnailField(thumbnail_filename)
setattr(getattr(instance, self.name), 'thumbnail', thumbnail_field)
It's right when the path is not dynamic. But when we use dynamic path such as headimg = models.FileField(upload_to='headimg/%Y%m'), return of self.generate_filename is corresponding to the date of today, so the thumbnail.path is changed every day.
Quick Fix:
In the source of stdimage/fields/py
def _set_thumbnail(self, instance=None, **kwargs):
"""Creates a "thumbnail" object as attribute of the ImageField instance
Thumbnail attribute will be of the same class of original image, so
"path", "url"... properties can be used
"""
if getattr(instance, self.name):
#fix the bug of wrong thumbnail path
#filename = self.generate_filename(instance,
# os.path.basename(getattr(instance, self.name).path))
file_path = getattr(instance, self.name).path
file_prefix = self.upload_to[:self.upload_to.find('/')]
filename = file_path[file_path.find(file_prefix):]
thumbnail_filename = self._get_thumbnail_filename(filename)
thumbnail_field = ThumbnailField(thumbnail_filename)
setattr(getattr(instance, self.name), 'thumbnail', thumbnail_field)
It works for me.
I submitted an issue to the stdimage project on github. Hope the author will fixed it.

Programmatically saving image to Django ImageField

Ok, I've tried about near everything and I cannot get this to work.
I have a Django model with an ImageField on it
I have code that downloads an image via HTTP (tested and works)
The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the ImageField)
All I need to do is associate the already existing image file path with the ImageField
I've written this code about 6 different ways.
The problem I'm running into is all of the code that I'm writing results in the following behavior:
(1) Django will make a 2nd file, (2) rename the new file, adding an _ to the end of the file name, then (3) not transfer any of the data over leaving it basically an empty re-named file. What's left in the 'upload_to' path is 2 files, one that is the actual image, and one that is the name of the image,but is empty, and of course the ImageField path is set to the empty file that Django try to create.
In case that was unclear, I'll try to illustrate:
## Image generation code runs....
/Upload
generated_image.jpg 4kb
## Attempt to set the ImageField path...
/Upload
generated_image.jpg 4kb
generated_image_.jpg 0kb
ImageField.Path = /Upload/generated_image_.jpg
How can I do this without having Django try to re-store the file? What I'd really like is something to this effect...
model.ImageField.path = generated_image_path
...but of course that doesn't work.
And yes I've gone through the other questions here like this one as well as the django doc on File
UPDATE
After further testing, it only does this behavior when running under Apache on Windows Server. While running under the 'runserver' on XP it does not execute this behavior.
I am stumped.
Here is the code which runs successfully on XP...
f = open(thumb_path, 'r')
model.thumbnail = File(f)
model.save()
I have some code that fetches an image off the web and stores it in a model. The important bits are:
from django.core.files import File # you need this somewhere
import urllib
# The following actually resides in a method of my model
result = urllib.urlretrieve(image_url) # image_url is a URL to an image
# self.photo is the ImageField
self.photo.save(
os.path.basename(self.url),
File(open(result[0], 'rb'))
)
self.save()
That's a bit confusing because it's pulled out of my model and a bit out of context, but the important parts are:
The image pulled from the web is not stored in the upload_to folder, it is instead stored as a tempfile by urllib.urlretrieve() and later discarded.
The ImageField.save() method takes a filename (the os.path.basename bit) and a django.core.files.File object.
Let me know if you have questions or need clarification.
Edit: for the sake of clarity, here is the model (minus any required import statements):
class CachedImage(models.Model):
url = models.CharField(max_length=255, unique=True)
photo = models.ImageField(upload_to=photo_path, blank=True)
def cache(self):
"""Store image locally if we have a URL"""
if self.url and not self.photo:
result = urllib.urlretrieve(self.url)
self.photo.save(
os.path.basename(self.url),
File(open(result[0], 'rb'))
)
self.save()
Super easy if model hasn't been created yet:
First, copy your image file to the upload path (assumed = 'path/' in following snippet).
Second, use something like:
class Layout(models.Model):
image = models.ImageField('img', upload_to='path/')
layout = Layout()
layout.image = "path/image.png"
layout.save()
tested and working in django 1.4, it might work also for an existing model.
Just a little remark. tvon answer works but, if you're working on windows, you probably want to open() the file with 'rb'. Like this:
class CachedImage(models.Model):
url = models.CharField(max_length=255, unique=True)
photo = models.ImageField(upload_to=photo_path, blank=True)
def cache(self):
"""Store image locally if we have a URL"""
if self.url and not self.photo:
result = urllib.urlretrieve(self.url)
self.photo.save(
os.path.basename(self.url),
File(open(result[0], 'rb'))
)
self.save()
or you'll get your file truncated at the first 0x1A byte.
Ok, If all you need to do is associate the already existing image file path with the ImageField, then this solution may be helpfull:
from django.core.files.base import ContentFile
with open('/path/to/already/existing/file') as f:
data = f.read()
# obj.image is the ImageField
obj.image.save('imgfilename.jpg', ContentFile(data))
Well, if be earnest, the already existing image file will not be associated with the ImageField, but the copy of this file will be created in upload_to dir as 'imgfilename.jpg' and will be associated with the ImageField.
Here is a method that works well and allows you to convert the file to a certain format as well (to avoid "cannot write mode P as JPEG" error):
import urllib2
from django.core.files.base import ContentFile
from PIL import Image
from StringIO import StringIO
def download_image(name, image, url):
input_file = StringIO(urllib2.urlopen(url).read())
output_file = StringIO()
img = Image.open(input_file)
if img.mode != "RGB":
img = img.convert("RGB")
img.save(output_file, "JPEG")
image.save(name+".jpg", ContentFile(output_file.getvalue()), save=False)
where image is the django ImageField or your_model_instance.image
here is a usage example:
p = ProfilePhoto(user=user)
download_image(str(user.id), p.image, image_url)
p.save()
Hope this helps
What I did was to create my own storage that will just not save the file to the disk:
from django.core.files.storage import FileSystemStorage
class CustomStorage(FileSystemStorage):
def _open(self, name, mode='rb'):
return File(open(self.path(name), mode))
def _save(self, name, content):
# here, you should implement how the file is to be saved
# like on other machines or something, and return the name of the file.
# In our case, we just return the name, and disable any kind of save
return name
def get_available_name(self, name):
return name
Then, in my models, for my ImageField, I've used the new custom storage:
from custom_storage import CustomStorage
custom_store = CustomStorage()
class Image(models.Model):
thumb = models.ImageField(storage=custom_store, upload_to='/some/path')
A lot of these answers were outdated, and I spent many hours in frustration (I'm fairly new to Django & web dev in general). However, I found this excellent gist by #iambibhas: https://gist.github.com/iambibhas/5051911
import requests
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
def save_image_from_url(model, url):
r = requests.get(url)
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(r.content)
img_temp.flush()
model.image.save("image.jpg", File(img_temp), save=True)
Another possible way to do that:
from django.core.files import File
with open('path_to_file', 'r') as f: # use 'rb' mode for python3
data = File(f)
model.image.save('filename', data, True)
If you want to just "set" the actual filename, without incurring the overhead of loading and re-saving the file (!!), or resorting to using a charfield (!!!), you might want to try something like this --
model_instance.myfile = model_instance.myfile.field.attr_class(model_instance, model_instance.myfile.field, 'my-filename.jpg')
This will light up your model_instance.myfile.url and all the rest of them just as if you'd actually uploaded the file.
Like #t-stone says, what we really want, is to be able to set instance.myfile.path = 'my-filename.jpg', but Django doesn't currently support that.
This is might not be the answer you are looking for. but you can use charfield to store the path of the file instead of ImageFile. In that way you can programmatically associate uploaded image to field without recreating the file.
With Django 3,
with a model such as this one:
class Item(models.Model):
name = models.CharField(max_length=255, unique=True)
photo= models.ImageField(upload_to='image_folder/', blank=True)
if the image has already been uploaded, we can directly do :
Item.objects.filter(...).update(photo='image_folder/sample_photo.png')
or
my_item = Item.objects.get(id=5)
my_item.photo='image_folder/sample_photo.png'
my_item.save()
You can try:
model.ImageField.path = os.path.join('/Upload', generated_image_path)
class tweet_photos(models.Model):
upload_path='absolute path'
image=models.ImageField(upload_to=upload_path)
image_url = models.URLField(null=True, blank=True)
def save(self, *args, **kwargs):
if self.image_url:
import urllib, os
from urlparse import urlparse
file_save_dir = self.upload_path
filename = urlparse(self.image_url).path.split('/')[-1]
urllib.urlretrieve(self.image_url, os.path.join(file_save_dir, filename))
self.image = os.path.join(file_save_dir, filename)
self.image_url = ''
super(tweet_photos, self).save()
class Pin(models.Model):
"""Pin Class"""
image_link = models.CharField(max_length=255, null=True, blank=True)
image = models.ImageField(upload_to='images/', blank=True)
title = models.CharField(max_length=255, null=True, blank=True)
source_name = models.CharField(max_length=255, null=True, blank=True)
source_link = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
tags = models.ForeignKey(Tag, blank=True, null=True)
def __unicode__(self):
"""Unicode class."""
return unicode(self.image_link)
def save(self, *args, **kwargs):
"""Store image locally if we have a URL"""
if self.image_link and not self.image:
result = urllib.urlretrieve(self.image_link)
self.image.save(os.path.basename(self.image_link), File(open(result[0], 'r')))
self.save()
super(Pin, self).save()
Working!
You can save image by using FileSystemStorage.
check the example below
def upload_pic(request):
if request.method == 'POST' and request.FILES['photo']:
photo = request.FILES['photo']
name = request.FILES['photo'].name
fs = FileSystemStorage()
##### you can update file saving location too by adding line below #####
fs.base_location = fs.base_location+'/company_coverphotos'
##################
filename = fs.save(name, photo)
uploaded_file_url = fs.url(filename)+'/company_coverphotos'
Profile.objects.filter(user=request.user).update(photo=photo)
class DemoImage(models.Model):
title = models.TextField(max_length=255, blank=False)
image = models.ImageField(blank=False, upload_to="images/DemoImages/")
import requests
import urllib.request
from django.core.files import File
url = "https://path/to/logo.jpg"
# Below 3 lines is to fake as browser agent
# as many sites block urllib class suspecting to be bots
opener = urllib.request.build_opener()
opener.addheaders = [("User-agent", "Mozilla/5.0")]
urllib.request.install_opener(opener)
# Issue command to actually download and create temp img file in memory
result = urllib.request.urlretrieve(url)
# DemoImage.objects.create(title="title", image=File(open(result[0], "rb")))
# ^^ This erroneously results in creating the file like
# images/DemoImages/path/to/temp/dir/logo_image_file
# as opposed to
# images/DemoImages/logo_image_file
# Solution to get the file in images/DemoImages/
reopen = open(result[0], "rb") # Returns a BufferedReader object of the temp image
django_file = File(reopen) # Create the file from the BufferedReader object
demoimg = DemoImage()
demoimg.title = "title"
demoimg.image.save("logo.png", django_file, save=True)
This approach also triggers file upload to cloudinary/S3 if so configured
So, if you have a model with an imagefield with an upload_to attribute set, such as:
class Avatar(models.Model):
image_file = models.ImageField(upload_to=user_directory_path_avatar)
then it is reasonably easy to change the image, at least in django 3.15.
In the view, when you process the image, you can obtain the image from:
self.request.FILES['avatar']
which is an instance of type InMemoryUploadedFile, as long as your html form has the enctype set and a field for avatar...
<form method="post" class="avatarform" id="avatarform" action="{% url avatar_update_view' %}" enctype="multipart/form-data">
{% csrf_token %}
<input id="avatarUpload" class="d-none" type="file" name="avatar">
</form>
Then, setting the new image in the view is as easy as the following (where profile is the profile model for the self.request.user)
profile.avatar.image_file.save(self.request.FILES['avatar'].name, self.request.FILES['avatar'])
There is no need to save the profile.avatar, the image_field already saves, and into the correct location because of the 'upload_to' callback function.
Your can use Django REST framework and python Requests library to Programmatically saving image to Django ImageField
Here is a Example:
import requests
def upload_image():
# PATH TO DJANGO REST API
url = "http://127.0.0.1:8080/api/gallery/"
# MODEL FIELDS DATA
data = {'first_name': "Rajiv", 'last_name': "Sharma"}
# UPLOAD FILES THROUGH REST API
photo = open('/path/to/photo', 'rb')
resume = open('/path/to/resume', 'rb')
files = {'photo': photo, 'resume': resume}
request = requests.post(url, data=data, files=files)
print(request.status_code, request.reason)
I save the image with uuid in django 2 python 3 because thats how django do it:
import uuid
from django.core.files import File
import urllib
httpUrl = "https://miimgeurl/image.jpg"
result = urllib.request.urlretrieve(httpUrl)
mymodel.imagefield.save(os.path.basename(str(uuid.uuid4())+".jpg"),File(open(result[0], 'rb')))
mymodel.save()
if you use admin.py you can solve the problem override (doc on django):
def save_model(self, request, obj, form, change):
obj.image_data = bytes(obj.image_name.read())
super().save_model(request, obj, form, change)
with models.py:
image_name = models.ImageField()
image_data = models.BinaryField()

Categories

Resources