My problem is that I need to know if a user has rated a certain model instance, BlogSite. On the page, there are multiple BlogSite instances, which have a 5-star rating system. When the current user has rated a certain instance, it should be set to read-only.
I'm running into a roadblock because if I use a model function, I need to pass 2 variables - current_user and BlogSite. I haven't been able to find how to access request.user in models.py and it's looking like I shouldn't be doing that?
The other path I went down was to create a custom filter - but I found out that I can only pass in one parameter. I would rather not do this method because I feel it would be better to keep the logic in views.py
Does anyone have ideas of how I can solve this problem?
#models.py
class BlogSite(models.Model):
#fields
#get the average rating for a blogsite
def rating_avg(self):
rating_dict = BlogSiteReview.objects.filter(blog_site=self).aggregate(Avg('review_rating'))
rating_avg = rating_dict.get('review_rating__avg')
if rating_avg:
return rating_avg
else:
#no ratings
return 0
def rated(self, current_user):
#If there is a row for the blogsitereview with this blogsite for the logged in user, return True, else False
#can I access the current user? This does not work, seems like I can't get request here.
current_user = request.user
review = BlogSiteReview.objects.filter(blog_site=self, user=current_user)
if review:
return True
else:
return False
class BlogSiteReview(models.Model):
blog_site = models.ForeignKey(BlogSite)
user = models.ForeignKey(User)
#other fields
Here is the relevant part of the view:
#views.py
def search(request, type, regionValue):
#....
#ideally, the solution would be to have a field or function in the BlogSite model
blog_sites = BlogSite.objects.filter(country=region.id, active=True)
#....
In the template I would have an if statement to add a class if rated returns True
<tr>
<td><a href="http://{{ blogsite.url }}" id="{{ blogsite.id }}">{{ blogsite.site_name }}</a></td>
<td><div id="rating{{ blogsite.id }}" class="rating {% if blogsite.user_rated %}jDisabled{% endif %}" data-average="{{ blogsite.rating_avg }}" data-id="{{ blogsite.id }}"></div></td>
<td>{{ blogsite.create_date }}</td>
</tr>
I'm looking for 2 things here - does using a model method to get if a user has rated seem like the correct approach? The problem I have with this so far is that I can't find how to access the current user to use in models.py. Another idea I thought of is to pass in the request.current_user from the view somehow, but the user is not associated with BlogSite, so I can't filter on that.