I have been using django imagekit without any problems in the templates but now I need to get the url in the view not the template, following this example in the imagekit docs:
source_file = open('/path/to/myimage.jpg')
image_generator = Thumbnail(source=source_file)
result = image_generator.generate()
So I did this:
course_img = open(settings.MEDIA_ROOT+str(course.image), 'rb+')
image_generator = myapp_images.Thumbnail100x100(source=course_img)
result = image_generator.generate()
And then, I try to get the url from the "result" variable, but I don't know how:
details_html += "<img class='img-rounded' src='"+ str(result) +"'/>
I have been trying with str(result), result.url, result.name, etc... with no luck, any idea how to get it?
Thx
I got the solution from the imagekit author in the google imagekit group:
In my case I wanted to interact with the Cache File, in order to do that we have to wrap my generator with an ImageCacheFile, like this:
from imagekit.cachefiles import ImageCacheFile
image_generator = myapp_images.Thumbnail00x100(source=course.image)
result = ImageCacheFile(image_generator)
so the result object it is what I was expecting, now I can read the url just using result.url.
Generator itself doesn't allow you to do that on the fly, it generates file-like object, which means it doesn't save the file on disk, which means no filename and so, no URL name..
Either you save the object and generate url manually or you can use ImageCacheFile like this:
from imagekit.cachefiles import ImageCacheFile
file = ImageCacheFile(image_generator, name='my_image.thumb.jpg')
file.generate()
print file.url
Related
So I have been creating a Fingerprint Matching system using Django Rest Framework. Whenever I send a fingerprint from frontend to backend to match with the stored fingerprints. The fingerprint is getting stored there which is not what I want. I want to delete it once it's use is over.
Here is the Error Image: https://i.stack.imgur.com/MCXcv.png
def post(self, request, format = None):
serializer = serializers.MatchSerializer(data = request.data)
if serializer.is_valid():
#Fetching the stored fingerprints in a different serializer.
queryset = models.Profile.objects.all()
serializer2 = serializers.ProfileSerializer(queryset, many=True)
data = serializer2.data
#Initialized a result list which will be appended with the name of the user whose
#fingerprint is matched.
result = []
file = request.FILES['fingerprint']
file_name = default_storage.save(file.name, file)
file = default_storage.open(file_name)
file_url = default_storage.url(file_name)
fImage = cv2.imread(str(file))
for i in range(len(data)):
print(data[i].get('fingerprint'))
DbImage = cv2.imread('C:/Users/ShalomAlexander/Documents/4th Year
Project/Django/FingerprintMatch/' + data[i].get('fingerprint'))
if(isMatch(fImage, DbImage)):
result.append(data[i].get('name'))
#This is not working as expected because its raising an error ie. " Process is still
#in use"
default_storage.delete(file_name)
return Response(result)
If you have any better approach to match fingerprints or images that will also be appreciated. Thanks in advance. The current code works fine and matches the fingerprint as expected but its storing the incoming fingerprint image and I don't want that.
For me this problem was solved using file_path instead of file_name:
file_name = default_storage.save(file.name, file)
file_path = os.path.join(settings.MEDIA_ROOT, file_name)
. . .
default_storage.delete(file_path)
file = default_storage.open(file_name)
...
default_storage.delete(file_name)
That is why that file is open when you try to delete it.
This has nothing to do with OpenCV. The point of a minimal reproducible example is to make you figure out where the issue is.
It looks like more an opencv issue than django-rest-framework's one.
Please refer to this issue:
https://github.com/opencv/opencv/issues/12342
Looks like your solution might be just to upgrade your opencv package version.
I am using PyMongo and I am trying to loop through an entire collection and display the ObjectId onto onto my Flask Web Page. However, when I write my method I keep getting the error "ObjectId('5efbe85b4aeb5d21e56fa81f')" is not a valid ObjectId.
The following is the code I am running
def get_class_names(self):
temp = list()
print("1")
for document_ in db.classes.find():
tempstr = document_.get("_id")
tempobjectid = ObjectId(tempstr)
temp.append(repr(tempobjectid))
print("2")
classes = list()
for class_ in temp:
classes.append(class_, Classes.get_by_id(class_).name)
return classes
How do I fix this?
Note: get_by_id, just takes in an ObjectId and finds it in the database.
The line
tempstr = document_.get("_id")
retrieves an ObjectId already. You then wrap it again in another ObjectId before calling repr on that. If you print(type(tempstr)), you'll see that it's an ObjectId.
Just do temp.append(tempstr).
BTW, you should rename the variable tempstr to tempId or something more appropriate.
I'm trying to retrieve a model object like the code below:
(r'^album/(?P<album_id>\w+)/$', 'core.views.album'),
def album(request, album_id):
album = Album.objects.get(pk=album_id)
The problem is that the PK is not an integer:
>>> a = Album.objects.all()[0]
>>> a.pk
46L
The error I'm getting when I run the view:
ValueError at /album/46L/
invalid literal for int() with base 10: '46L'
Ideas? Thanks.
46L is a long integer, not a string, so you should treat it as a number and not a word in urls.py:
(r'^album/(?P<album_id>\d+)/$', 'core.views.album'),
then the url /album/46/ will end up calling:
def album(request, album_id):
#album = Album.objects.get(pk=46L)
album = Album.objects.get(pk=album_id)
Or if you need to keep the 'L' in the url for some reason, cast it as a long before using it:
album = Album.objects.get(pk=long(album_id))
The problem was unrelated with the urls / views. Everytime I executed "runserver" my local datastore was being erased. So the data I was able to retrieve when using "shell" was not synced correctly.
This happened because, for some weird reason, I commented this line (and forgot about it) on settings.py:
AUTOLOAD_SITECONF = 'indexes'
I'm using flatpages app in my project to manage some html content. That content will include images, so I've made a ContentImage model allowing user to upload images using admin panel.
The user should then be able to include those images in content of the flatpages. He can of course do that by manually typing image url into <img> tag, but that's not what I'm looking for.
To make including images more convenient, I'm thinking about something like this:
User edits an additional, let's say pre_content field of CustomFlatPage model (I'm using custom flatpage model already)
instead of defining <img> tags directly, he uses a custom tag, something like [img=...] where ... is name of the ContentImage instance
now the hardest part: before CustomFlatPage is saved, pre_content field is checked for all [img=...] occurences and they are processed like this:
ContentImage model is searched if there's image instance with given name and if so, [img=...] is replaced with proper <img> tag.
flatpage actual content is filled with processed pre_content and then flatpage is saved (pre_content is leaved unchanged, as edited by user)
The part that I can't cope with is text processing. Should I use regular expressions? Apparently they can be slow for large strings.
And how to organize logic? I assume it's rather algorithmic question, but I'm not familliar with text processing in Python enough, to do it myself.
Can somebody give me any clues?
I finally imlemented this using regular expressions. I decided, that spaces are not allowed inside the custom tag. Main text processing function looks like this:
import re
from django.utils.translation import ugettext as _
def process_image_tags(text, ImageModel):
'''image tag usage:
... some text ... [img=image_name:image_class(optional)] ... some text ...
'''
t1 = re.split(r'(\[img=[a-z0-9\-_\:]+\])', text)
t2 = []
for i in t1:
if i[:5] == '[img=':
attrs = i[5:-1].split(':')
name_attr = attrs[0] #name attribute
error = None
try:
image = ImageModel.objects.get(name=name_attr)
except ImageModel.DoesNotExist:
error = '<span class="image_tag_error">%s</span>' % _('Image with given name not found')
except ImageModel.MultipleObjectsReturned:
error = '<span class="image_tag_error">%s</span>' % _('More than one image found')
if not error:
p = ['<img']
p.append('src="%s"' % image.image.url)
if len(attrs) > 1:
p.append('class="%s"' % attrs[1]) #class attribute
if image.description:
p.append('title="%s"' % image.description)
p.append('alt="%s"' % image.name)
p.append('/>')
t2.append(' '.join(p))
else:
t2.append(error)
else:
t2.append(i)
return ''.join(t2)
Above function is then used in save method of CustomFlatPage model, like this:
def save(self, *args, **kwargs):
self.content = process_image_tags(self.pre_content, ContentImage)
super(CustomFlatPage, self).save(*args, **kwargs)
It seems to work, so I'll probably end up using that solution. Maybe I'll add some javascript for user to insert image tags by picking images from generated list of images, but even now it's better than manually typing urls, I think.
Following http://mongoengine.org/docs/v0.4/guide/gridfs.html documentation about mongoengine FileField I did the following:
In my model
files = ListField(FileField())
In my test code
# Create an entry
photo = FileField()
f = open('/home/foo/marmot.jpg', 'r')
photo.put(f, content_type='image/jpeg')
entry.files = [photo,]
Trying to follow the doc, however i get an error:
Traceback (most recent call last):
File "/home/bar/tests.py", line 76, in test_MongoDGACLogook_creation
photo.put(f, content_type='image/jpeg')
AttributeError: 'FileField' object has no attribute 'put'
Am I missing something obvious ?
Thanks
This isn't obvious at all IMO, but if you look at the Mongoengine code you'll see that the put method is defined in the GridFSProxy class, which is accessed via a descriptor in FileField (the __get__ and __set__ methods).
Looking at the code and the examples in the docs, it appears the only way to access or use a FileField is through the descriptor....so, collection.file_field.
Given all this, I don't think it's possible to have a list of file fields using the Mongoengine API as it exists now.
f = mongoengine.fields.GridFSProxy()
to_read = open('/home/.../marmot.jpg', 'r')
f.put(to_read, filename=os.path.basename(to_read.name))
to_read.close()
If you are uploading multiples files and trying to save it a ListField(FileField())
<input type='file' name='myfiles' multiple="">
files = []
for f in request.FILES.getlist('myfiles'):
mf = mongoengine.fields.GridFSProxy()
mf.put(f, filename=f.name)
files.append(mf)
entry.files = files
entry.save()
I had exactly the same problem. As suggested by #KoppeKTop on GitHub in this post, I finally extended my model (Pet) using an EmbeddedDocument like this:
class OneImage(mongoengine.EmbeddedDocument):
element = ImageField()
class Pet(mongoengine.Document):
photos = EmbeddedDocumentListField(OneImage)
# ...more fields... #
I can then add a new image using
i = OneImage()
i.element.put(form.photo.data.stream)
entry.photos.append(i)
entry.save()
This may not always be the best option, but personally I prefer it because I can work with models as usual without having to work with proxies. And I can also save other photo metadata in the future, if I need to.