Entity images + Blobstore - google-app-engine

I'm quite confused about how the Blobstore works alongside serving images per entity.
So let's say I have:
class Book(ndb.Model):
title = ndb.StringProperty()
cover_image = ndb.BlobProperty()
How can I output this information in a jinja2 template, like this:
<h1>{{title}}</h1>
{{cover_image}}
My confusion stems from my being unclear about how the Blobstore and the datastore works together. For example: How do we relate a datastore's entity to a Blobstore property (in our example, it would be relating the the cover_image blobproperty to its Book entity)?
A simplified explanation would be much appreciated. Thank you.

What you are looking for is get_serving_url(blob_key, size=None, crop=False, secure_url=None)
Try this method on the blob and you will get an image url.
Docs
You upload the blob and you get a blobkey that you store. Imagine it like another entity's key.
Then having that key you use the get_serving url and several other functions in order to serve a url, resize etc.

You can just use a BlobKeyProperty in your model to maintain a reference between the datastore and the blobstore. For example:
class MyContent (ndb.Model):
Image = ndb.BlobKeyProperty()
Then, if you need to frequently get the associated URL you can even also store the serving URL:
class MyContent (ndb.Model):
Image = ndb.BlobKeyProperty()
ImageServingURL = ndb.StringProperty()

You can create a different handler for getting the images. The way you do that depends on the framework used. Pyramid example (without try and excepts):
#handler /{bookid}/coverimage
def RenderImage(request):
book_key = request.matchdict['bookid']
book = Key(urlsafe=book_key}.get()
cover = book.cover_image
#optional rezising:
cover = images.resize(cover, WIDTH, HEIGHT) #or other image operations
response = Response(content_type="image/jpeg")
response.body = cover
return response
In your template:
<img src="/{{book.key.urlsafe()}}/coverimage" />
Note: you can do a generic image handler for any image property, not only 'cover_image'

Related

Get src of image file stored in dtabase?

I have a dessert model in django with a property called picture:
class Dessert(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(max_length=1000, blank=True)
picture = models.ImageField(upload_to ='uploads/desserts-pics/', max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(1)])
tags = models.ManyToManyField(Tag, related_name="desserts")
def __str__(self):
return self.name + " ($" + str(self.price) +")"
And i want to show the image in my front with react, like this:
<img src={dessert.picture}>
dessert is an instance of the Dessert model witch i got from a request, but the picture is a file not an image, how the hell do i get the src? sorry, i know it's a silly question but i didn't find the answer anywhere else.
I am not a react user. However, the HTML tag you show (if it's similar) would need some changes to display the image field of your model instance. Let's assume you have a simple view that shows a dessert, like...
def show_dessert(request):
d = Dessert.objects.get(id=1)
context = {'d':d}
return render(request, "pages/my_template.html", context)
With d as your desert object, you would show the image using .url, like:
<img src="{{d.picture.url}}">
Find more information on serving files and photos in Django docs here.
This answer also assumes you have correctly configured your static files settings. More info about that here.

Django - Setting a value of Model inside template page

I have a simple Django App having database interactions. I need to make the functionality of Video Visiting counter. So that I need to update- increment the counter each time when user visit the video.
I have a video object on template page(video-details.html).
This is how I access the video_file_name.
<h1 id="video1">{{video_obj.video_file_name}}</h1>
I have video model as:
class Video_Mapping(models.Model):
video_file_name = models.CharField(max_length=100)
video_description = models.CharField(max_length=2000, default='Video Description')
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
video_category_id = models.IntegerField(default=1)
video_seen_count = models.IntegerField(default=0)
I want to update the video_seen_count model value on template page.
More info: As I can do similar thing in View like following.
video = Video_Mapping.objects.get(pk=video_id);
video.video_description = description; video.save();
Please suggest me the best way to do it in the video-detail.html template page.
The simplest thing which I have done here is as per #birophilo'suggestion.
I was actually finding the way to increment the video_seen_count value from template(html page).
But after doing more research and try as suggested in comment, I decided to make this increment operation before the template renders(So in the view).
So it worked like:
video.video_screen_count += 1
video.save();
Thanks.

Tastypie filter by minimum value

I have a Django-tastypie resource that represents a banner and has a field called impression that I increment whenever the banner appears on the site.
class BannerResource(ModelResource):
owner = fields.ForeignKey('advertisment.api.AdvertiserResource', 'owner', full=True)
class Meta:
queryset = Banner.objects.all()
resource_name = 'banner'
authorization = Authorization()
I would like to get the banner that has the minimum impression, in the official documentation there is nothing like
filtering = {'impressions': ('min',)}
I'm using BackboneJS in the front end and I could get all the banners with Backbone collection and do the filtering with JavaScript but I'm looking for a quicker way to do it.
Any ideas?
Thanks
If you'd like to retrieve banners with number of impressions greater than X you need to things. For one you need to define possible filtering operations on your resource like so (given your model has impressions field):
class BannerResource(ModelResource):
owner = fields.ForeignKey('advertisment.api.AdvertiserResource', 'owner', full=True)
class Meta:
queryset = Banner.objects.all()
resource_name = 'banner'
authorization = Authorization()
filtering = { 'impressions' : ALL }
for available options take a look at Tastypie's documentation on filtering.
Then if you made the following request:
GET http://<your_host>/v1/banners?impressions__gte=X
you should get what you need.

Django image modification, from one image field to others

I have a image field in the model. I need to make two copies(resized) of that image to another two field(thumb_big and thumb_small). Thumb_big will be 225px width, height could be anything. and thumb_small is 65x50px.
I searched but nothing seems to fit in my problem. I Have installed PIL. Tried django-imagekit, some other snipets.
If you know any link that will be great also, BTW I am a django newbie but you assume that already, right?
here is my model
class Photo(models.Model):
title = models.CharField(max_length=500)
pub_date = models.DateField(auto_now_add=True)
mod_date = models.DateField(auto_now=True)
slug_name = models.SlugField(max_length=500)
image = models.ImageField(upload_to='interview', blank=True)
thumb_big = models.ImageField(upload_to= 'interview/thumbs_big', blank=True)
thumb_small = models.ImageField(upload_to= 'interview/thumbs_small', blank=True)
category = models.CharField(max_length=200, blank=True)
details = models.TextField()
def __unicode__(self):
return self.title
I'm not quite sure why would you need to store thumbnail paths in the database.
There are several django thumbnail applications.
Two of my favorites are:
sorl-thumbnail - https://github.com/sorl/sorl-thumbnail
easy-thumbnails - https://github.com/SmileyChris/easy-thumbnails
Both of them are using template tags for generating thumbnails on the fly,
and display them in your django templates.
They also come with custom database fields to make thumbnail management easier:
http://thumbnail.sorl.net/examples.html#model-examples
http://packages.python.org/easy-thumbnails/usage.html#models
If you really need to save paths to your thumbnails in your model, you can generate both thumbnails in your image upload view, and then assign resulting file paths to corresponding database fields. With easy thumbnail it will look like:
photo = form.save()
from easy_thumbnails.files import get_thumbnailer
thumbnailer = get_thumbnailer(photo.image)
thumb = thumbnailer.get_thumbnail({'size': (100, 100)})
photo.thumb_big = thumb.name
photo.save()

AppEngine Datastore get entities that have ALL items in list property

I want to implement some kind of tagging functionality to my app. I want to do something like...
class Item(db.Model):
name = db.StringProperty()
tags = db.ListProperty(str)
Suppose I get a search that have 2 or more tags. Eg. "restaurant" and "mexican".
Now, I want to get Items that have ALL, in this case 2, given tags.
How do I do that? Or is there a better way to implement what I want?
I believe you want tags to be stored as 'db.ListProperty(db.Category)' and then query them with something like:
return db.Query(Item)\
.filter('tags = ', expected_tag1)\
.filter('tags = ', expected_tag2)\
.order('name')\
.fetch(256)
(Unfortunately I can't find any good documentation for the db.Category type. So I cannot definitively say this is the right way to go.) Also note, that in order to create a db.Category you need to use:
new_item.tags.append(db.Category(unicode(new_tag_text)))
use db.ListProperty(db.Key) instead,which stores a list of entity's keys.
models:
class Profile(db.Model):
data_list=db.ListProperty(db.Key)
class Data(db.Model):
name=db.StringProperty()
views:
prof=Profile()
data=Data.gql("")#The Data entities you want to fetch
for data in data:
prof.data_list.append(data)
/// Here data_list stores the keys of Data entity
Data.get(prof.data_list) will get all the Data entities whose key are in the data_list attribute

Resources