Django - Setting a value of Model inside template page - django-models

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.

Related

Entity images + Blobstore

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'

Taggit gets wrong tags

I have a Work model with Category Foreign Key. I am doing -->
drawingTags = Tag.objects.filter(Q(work__category__slug_en = 'drawing') |
Q(work__category__slug_en = 'illustration') |
Q(work__category__slug_en = 'sketch') |
Q(work__category__slug_en = 'storyboard'))
I get also the tags that do not belong to drawings ? Am i doing smt wrong ?
-- EDIT --
I did a little test. I have two applications named blog and web.
In blog i have 'entry' model and in web i have 'work' model. Both of those models have TaggableManager fields named tags...
When i want to take the tags of works categorized under drawing and do -->
drawingTags = Tag.objects.filter( work__in = drawings ).distinct()
If there is a drawing with id 1 and if entry model has an entry with id 1. Than i get both item's tags. I think there is a problem here but i do not know how to solve the puzzle?
Solution :
from django.contrib.contenttypes.models import ContentType
contentType = ContentType.objects.get_for_model(Work)
drawingTags =Tag.objects.filter(taggit_taggeditem_items__content_type=contentType,
work__in = drawings ).distinct()

Allowing a user to schedule an event and have it linked to their account information for use in a django template

I've looked into the answers posted to similar questions but I couldn't get anything to work for my situation, so I will post my question. The way I have it, I always get the result "None" when I try to get the first name of the user who created an event... So I have multiple classes of users and I want to allow one type of user to be able to schedule events, with the template showing the user who created the event along with the various other fields that are in the class relating to the event. So for example:
#models.py
class BaseProfile(models.Model):
user = models.ForeignKey(User, unique=True)
first_name = models.CharField(max_length=20, verbose_name=_('First Name'))
last_name = models.CharField(max_length=20, verbose_name=_('Last Name'))
...
#More common fields
#Used for when a new broadcaster registers; fields specific to broadcasters
classBroadcasterProfile(models.Model):
user_type = models.CharField(max_length=20, default="broadcaster")
...
#Other fields specific to broadcasters
#Used when a broadcaster creates a profile for themselves after they have registered
class BroadcasterAccountProfile(BroadcasterProfile):
...
#A broadcaster wants to schedule an event
class UpcomingEvents(models.Model):
title = models.CharField(max_length=50, verbose_name=_('Title'))
description = models.TextField(max_length=100, verbose_name=_('Event Description'))
instructor = models.ForeignKey(BroadcasterAccountProfile, null=True, blank=True, related_name='instructor')
event_date = models.DateField(auto_now=False, auto_now_add=False, verbose_name=_('Date of Event'))
...
#Additional info to be included with the scheduling of event
So after a broadcaster has registered, created a profile, and scheduled an event (which all works successfully), the view I am trying to use for displaying the upcoming scheduled events is as follows:
#views.py
def upcoming_event_list(request):
today = datetime.date.today()
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
todays_events = UpcomingEvents.objects.filter(event_date=today)
tomorrows_events = UpcomingEvents.objects.filter(event_date=tomorrow)
return render_to_response('events/preview.html', {'today': today, 'tomorrow': tomorrow,
...
I can have my template display anything related to the upcoming events except for anything related to the broadcaster who created the event. I have tried adding values to my views:
def upcoming_event_list(request):
...
values = UpcomingEvents.objects.values('instructor__first_name', 'instructor__last_name', 'instructor__avatar')
#template.html
{% for v in values %}
Broadcaster Name:{{ v.instructor__first_name }}
{% endfor %}
This would show "Broadcaster Name: None". Am I completely heading in the wrong direction, or what can I do to try to make this work? Sorry if this was confusing. I tried to make it as clear as possible, but seeing as how I am confused myself, I don't know how successful I was in trying to describe my problem. Thanks for any help. Please let me know if I need to clarify anything.
Have you tried {{ v.instructor.first_name }} in your template?
Note the .(full-stop/dot/period/whatever-you-call-it) instead of a __(double underscore).

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

Resources