Search code examples
pythonhtmlwebapp2

An unexpected keyword argument python


I'm trying to implement a simple function to like a post. I have 4 models defined using Google App Engine; User, Blogpost, Like, Comments

below is the snippets:

class LikePost(db.Model):
    user        = db.ReferenceProperty(User)
    blogpost    = db.ReferenceProperty(Blogpost)
    date        = db.DateTimeProperty(auto_now_add = True)

class Comment(db.Model):
    user        = db.ReferenceProperty(User)
    blogpost    = db.ReferenceProperty(Blogpost)
    content     = db.TextProperty(required = True)
    date        = db.DateTimeProperty(auto_now_add = True)

I tried to call the method to like a post using below:

class LikePost(Handler):
    def get(self,post_id):
        blogpost = self.get_blogpost(post_id)
        user = self.get_user_object()
        if blogpost and user:
            like = LikePost(user = user, blogpost = blogpost)
            like.put()
            self.redirect('/%s' % post_id)
        else:
            self.redirect('/login')

The reference to the method is as follow:

def get_user_object(self):
        cookie = self.request.cookies.get('user_id')
        if cookie:
            user_id = check_secure_val(cookie)

            if user_id:
                user_id = cookie.split('|')[0]
                key = db.Key.from_path('User', int(user_id))
                user = db.get(key)
                return user

def get_blogpost(self, post_id): key = db.Key.from_path('Blogpost', int(post_id)) blogpost = db.get(key) return blogpost

I got an error when trying to run the above :

__init__() got an unexpected keyword argument 'blogpost'

Anyone can explain what went wrong ?


Solution

  • You have defined your model as

    class LikePost(db.Model):
    

    Then you have defined your handler has

    class LikePost(Handler):
    

    Notice that they have the same name. So inside your get method what's in scope is your Handler subclass, which apparently does not expect a blogpost keyword argument to it's __init__ method. Simplest solution, rename one or the other or

     from models import LikePost as LP
    

    and use that