How to perform star rating using django and ajax? - ajax

I want to perform a star rating in my blog application for better user experience...But couldn't perform in django using ajax...I basically don't want to use any third party application for my blog project...I want to do manually using django and ajax...
This is my blog model:
class Blog(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
date = models.DateTimeField(default=datetime.now)
blog_title = models.CharField(max_length=255,unique=True)
likes = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='likes',blank=True)
description = models.TextField()
blog_image = models.ImageField(upload_to='blog_image', null=True, blank=True)
category = models.ForeignKey(categories,on_delete=models.CASCADE,related_name='blogs')
blog_views = models.IntegerField(default=0)
Any idea anyone how to perform this?
Thank you in advance

I assume that you're trying to rate the blog 1-5.
If you want to save each and every vote for the blog, you'll have to keep an additional model for the votes, something like:
class BlogStars(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
stars = models.IntegerField(default=0)
For each and every vote, you'll save the user, the blog voted for and the amount of stars.
After that, all you need to do is to query the BlogStars:
stars = BlogStars.objects.filter(blog=my_blog).aggregate(Avg('stars'))
Saving the data using Ajax, is just making ajax calls to the backend view.
In any case, check this tutorial as an example, although it uses PHP, it'll give you a good idea.

Related

Django-Oscar Basket customization

I am using Djnago-oscar for Solar energy equipment based eCommerce site. I need to add an option to "Basket" model with "Battery Name", "Notes" and
"Manufacturer". There is a reason I don't want to add it in subclass AbstractProduct. Rather I want to built it with subclass Basket model.
Now I need help to understand my workflow to make this work with AddToBasket form. In Django-oscar/basket there are formsets.py using formset factory and a form.
I am a bit confused and decided to get help from community.
Following is the code:
models.py
MANUFACTURERS = (
('UPS SYSTEMS', 'UPS SYSTEMS'),
('VOLTA', 'VOLTA'),
('TOSHIBA ', 'TOSHIBA '),
)
BATTERIES = (
('LITHIUM', 'LITHIUM'),
('NICAD', 'NICAD'),
('NIFE ', 'NIFE '),
)
class AddBattery(AbstractBasket):
battery_name = models.CharField(max_length=1, choices=BATTERIES)
manufacturers = models.CharField(max_length=1, choices=MANUFACTURERS)
price = models.DecimalField(decimal_places=2, max_digits=6)
notes = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.battery_name
class Basket(AbstractBasket):
add_bat=models.ForeignKey(_(u'Add a Batter'), to=AddBattery, null=True, blank=True)
forms.py
from django import forms
from django.conf import settings
from django.db.models import Sum
from django.utils.translation import ugettext_lazy as _
from oscar.forms import widgets
from oscar.apps.basket.forms import BasketLineForm as CoreBasketLineForm,\
SavedLineForm as CoreSavedLineForm, BasketVoucherForm as CoreBasketVoucherForm,\
AddToBasketForm as CoreAddToBasketForm
from .models import AddBattery
from oscar.core.loading import get_model, get_classes
Line = get_model('basket', 'line')
Basket = get_model('basket', 'basket')
Product = get_model('catalogue', 'product')
class BasketLineForm(CoreBasketLineForm):
class AddBatteryForm(CoreBasketLineForm.Meta):
model = AddBattery
fields = ['battery_name', 'manufacturers', 'comment']
views.py
I need help to figure this part because it has so much nested elements and I couldn't get it right.
Help is much appreciated.
Templates:
I can work this out because I need admin to have ability to add it but end user only will have an option to select from with price.
Upon selection by client I need to have consolidated price with products and plus the battery. Any advise for this part would be great as well
about how to get consolidated price from both in cart for checkout.
Don't add your fields in Basket model. You need to subclass Line model instead.
Subclass forms.py and formsets.py. You only need to change BasketLineForm, SavedLineForm and AddBasketForm. After you subclass these in your own forms. Leave rest of the Forms.
Subclass BaseBasketLineFormSet and BaseSavedLineFormSet in your own formsets edit as per your need.
Subclass BasketView and AddBasketView by supplying the forms, formsets and args/kwargs you added.
Copy template directory from app to your own folder and add form at basket_total.html as you mentioned above as the last part.
But having said that...its against the workflow as explained by others. There is no limitation at all for you in any case as far as programming is concerned. But you should always consider the most reasonable path to solve your problems.
This is a very broad question with several different components. I can offer the following suggestions for you to look into:
Doing this in the basket model is almost certainly not going to serve you well, because you will not be able to pass this custom information to the order object when it is created. More importantly, what you're trying to do doesn't seem to be a basket issue, just a product/variant issue (see below).
There are two possibilities I can see from what you have described:
a. A battery is a separate product that the user buys along with the main product. It has its own pricing and availability.
b. A battery isn't a separate product, it's just one of a fixed set of choices that a customer has when buying the main product.
If (a), then you just need to have separate products, and some logic that allows a user to select the accessory product (battery) at the same time as the main one, and that adds both to the basket simultaneously.
If (b), then these are essentially variants where one product has multiple variations with different pricing. In this case you should use Oscar's built-in support for variants.
In any case, modifying the basket model will cause you a lot of problems IMO.

How to get only Tweet (only posts) from the timeline?

Whenever tweet is created, it's activity is added to getStream production app.
class Tweet(models.Model, Activity):
user = models.ForeignKey()
text = models.CharField()
class Follow(models.Model, Activity): <- This is adding new activity to the timeline
def follow_feed_lisnner(~)
signal.post_save.connect(~)
class Like(models.Model, Activity): <- Like is adding to activity so timeline automatically shows who liked this post,
My Expectation:
Feed: only shows Tweet on timeline (I don't want to see who started to follow me, or liked any post) - Just Like Instagram!
Notification: Who started to follow me, Who liked my post, Who commented on my post.
views.py
feeds = feed_manager.get_news_feeds(request.user.id)
# get the newsfeed for user.
activities = feeds.get('timeline').get()['results']
activities = enricher.enrich_activities(activities)
Possible Solutions
Use python-stream (more low level) to deal with this problem. (I don't know if it helps)
Maybe I'm missing a cool feature of stream-django
How can we get only Tweet (Not Like, Follow or other activities which should be in notification) on the timeline?
Thank you
UPDATE
If I understood correctly, this should work. Is this valid?
class Follow(models.Model, Activity):
follower =
following
#property
def activity_author_feed(self):
return 'notification'
Activity 1: user A follows user B.
Activity 1 goes to 'user' feed + 'notification' feed (not timeline feed)
//notification feed name already exists so I don't need to create follow feed group
Activity 2: user B creates Post
Activity 2 goes to 'user' feed + 'timeline' feed
Note: I'm assuming your Follow and Like models have a "user" field. If not, best update the question with the full Model classes and also confirm if you're setting up any other following relationships.
The stream-django integration provides an 'Activity' model Mixin and the FeedManager model Manager. They work together to add activities to a Feed Group and Feed whose unique "feed id" is derived from the Model instance.
By default, the feed id is determined by the application wide settings.USER_FEED setting. That should work well for your Tweet model but is probably not what you want for the Follow and Like models. The activities associated with those models ideally belong in separate feeds. This can be setup by overriding the Activity.activity_author_feed property function.
class Follow(models.Model, Activity):
# snipping fields
#property
def activity_author_feed(self):
return 'Follow' # Must match a Feed Group defined in the Stream dashboard
#property
def activity_actor_attr(self):
return self.author
To have to those activities copied into the notification feed, implement the Activity.activity_notify() function to return a list of target feeds.
#property
def activity_notify(self):
return [feed_manager.get_notification_feed(self.user.id)]

Customer page URL

So, I have a Braintree customer id and access to the Braintree API (Python).
Knowing the customer id, how do construct URL for customer page on Braintree site? Something like https://sandbox.braintreegateway.com/merchants/{merchant_id}/customers/{customer_id}
Do I do this manually or there is an API for this?
This is my current solution:
if user.braintree_customer_id:
bt_customer_url = braintree.Configuration.gateway().customer.config.base_merchant_url(
) + '/customers/%s' % user.braintree_customer_id
url_parts = urlparse.urlsplit(bt_customer_url)
if url_parts.netloc.startswith('api.'):
url_parts = list(url_parts)
url_parts[1] = url_parts[1][4:]
bt_customer_url = urlparse.urlunsplit(url_parts)
I work at Braintree. There is no API call for the URL you are looking for, but you can structure it the way you have done. I can't guarantee that the url structure will never change, but it should be simple to update your script if it does.

Update model attribute without refreshing database

I'm building a website listing poker tournaments. I would like to allow user mark some tournaments as his favourite and avoid forms or extra page with GET parameter - I would like to to update it without refreshing website. From what I understand, it's done by ajax and jquery. But there are many ajax libraries and I would like you to tell me, which one should I use and how to do this simple functionality best.
This is my tournament table:
I would like to have another column before event time, that would contain image for heart. It would be black (not favourite) and if user clicks on it, it would turn red (favourite).
I think m2m relationship should be used here. This is my tournament model.
class Tournament(models.Model):
favourite = models.ManyToManyField(User)
date = models.DateTimeField('Event time')
currency = models.CharField(max_length=5, choices=CURRENCIES, default='USD')
name = models.CharField("Tournament name", max_length=200)
prize = models.DecimalField(max_digits=20, decimal_places=2)
entry = models.DecimalField(max_digits=20, decimal_places=2)
fee = models.DecimalField(max_digits=20, decimal_places=2)
password = models.CharField("password", max_length=200)
type = models.ForeignKey('room.Type')
room = models.ForeignKey('room.Room')
requirements_difficulty = models.IntegerField('Tournament Difficulty',
validators=[MinValueValidator(1), MaxValueValidator(30)])
requirements_text = models.CharField("Requirements Description", max_length=1000)
recurrence = models.CharField(max_length=5,
choices=RECURRENCE_CHOICES,
default='NONE')
So how do I add m2m relationship between user and tournament? Do I use ajax code or dajax? How do I create this m2m without refreshing page?
So how do I add m2m relationship between user and tournament?
Assuming that you use the default django user model:
Class Tournament(models.Model):
user = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='user_tournament')
...
Do I use ajax code or dajax?
As #doniyor said, you should define your real problem and split your question. SO is not "do it for me", anyway, what I can do for you, is give you some good links ;)
W3 schools definition for ajax:
http://www.w3schools.com/ajax/ajax_intro.asp
Good ajax plugin for djando that seems you already know:
http://www.dajaxproject.com/
By the way, you should use dajax, is easy and faster to create ajax pages integrated with django (you just have to follow the tutorials, is pretty simple).
How do I create this m2m without refreshing page?
Using dajax

GAE blobstore is killing me

I followed this tutorial :
https://developers.google.com/appengine/docs/python/images/usingimages
And it's killing me...I managed to make it work...however I was not able to make it suite my needs...problem is that i want to serialize my Model using json...
Why do they put the avatar = db.BlobProperty() in the model and not use a reference to that blob ?...Is there any reason whatsoever?
I could not find a decent tutorial, on how to store an image in Blob, and then store its location/ key/reference in a Model..Any suggestions?
With the code from below...i am doing exacty what is in the tutorial...how do I get the reference to that pic , and how do I store it???
pic = self.request.get('img')
pic = db.Blob(pic)
What i managed to do is to store the id of the entity in JSON, and use that id to retrieve and display the pic. And i display the pic with the following code:
class Image(webapp2.RequestHandler):
def get(self):
#product = db.get(self.request.get('img_id'))
product = MenuProduct.by_id(int(self.request.get('img_id')))
if product.small_pic:
self.response.headers['Content-Type'] = 'image/png'
self.response.out.write(product.small_pic)
else:
self.error(404)
I am guessing that all efficiency goes to hell by using this approach ...Right?
Sorry is my post sounds messy...but I am kind of tired of the "great" poor documentation related to this topic.
Rather than store the blob as a BlobProperty, you should use the separate Blobstore service and store the BlobKey in the model.

Resources