views:

56

answers:

2

I am trying to create a vote function that increases the class URL.votes +1 when clicked. This is a two part question:

  1. How do you pull the entity key? (I think you need the key to distinguish which vote property is being modified?)

  2. How do you then write the 'a href' for the link to perform the vote?

Thanks!


Models:

class URL(db.Model):

user = db.ReferenceProperty(User)
website = db.StringProperty()
created = db.DateTimeProperty(auto_now=True)
votes = db.IntegerProperty(default=1)

class Vote(db.Model):

user = db.ReferenceProperty(User) #See if voted on this site yet
url = db.ReferenceProperty(URL) #To apply vote to right URL
upvote = db.IntegerProperty(default=1)
created = db.DateTimeProperty(auto_now=True)

Controller

class VoteHandler(webapp.RequestHandler):

def get(self):
    doRender(self, 'base/index.html')

def post(self):

    #See if logged in
    self.Session = Session()
    if not 'userkey' in self.Session:
        doRender(
            self,
            '/',
            {'error' : 'Please login to vote'})
        return

    #Get current vote total

    url = db.URL.get() #pull current site. This is where I think I need the help 
    url.votes += 1 #pull current site vote total & add 1
    url.put();

    logging.info('Adding a vote'+nurl)

    #Create a new Vote object
    newvote = models.Vote(user=self.Session['userkey'], url=url)
    newvote.put();

    self.get(); 

    self.redirect('/', { })

View

a href="/vote" {{ url.votes }} votes - {{ url.website }}

A: 

You can use url.votes.key.id in your View

a href="/vote*?id={{ url.votes.key.id }}*" {{ url.votes }} votes - {{ url.website }}

mcotton
ok great thanks
Emile Petrone
+1  A: 

The answer includes a few things:

  1. You need to use a Query string to pass the data on for the VoteHandler

a href="/vote?url_id={{url.key.id}}">{{ url.votes }} votes - {{ url.website }} - {{ url.user.account }} - {{ url.created|date:"M d, Y" }}

  1. Clicking a vote link, is a get() not a post(). Then you use model.get_by_id()

class VoteHandler(webapp.RequestHandler):

def get(self):
    #See if logged in
    self.Session = Session()
    if not 'userkey' in self.Session:
        doRender(
            self,
            'base/index.html',
            {'error' : 'Please login to vote'})
        return

    #Get current vote total
    key = self.request.get('url_id')
    vurl = models.URL.get_by_id(int(key))
    vurl.votes += 1 #pull current site vote total & add 1
    vurl.put();

    logging.info('Adding a vote')

    #Create a new Vote object
    newvote = models.Vote(user=self.Session['userkey'], url=vurl)
    newvote.put();

    self.redirect('/', { })
Emile Petrone