Clicking favourite button adds (and saves) an object to a many to many field in a user model in Django

132 Views Asked by At

When you click a google map marker (in this case it is a tree object) an info window pops up, there is a heart button on the window, giving the user the opportunity to heart (favour) this tree. By doing to it will add the tree object to the userprofile's tree field (which is a many to many field). But unfortunately, I am have having trouble adding the tree object to the userprofile's tree field.

Here is the run-down in code:

Heart button (on index.html)

'<button type="submit" class="btn btn-default btn-sm" onclick="favButton({{tree.treeId}});"><span class="glyphicon glyphicon-heart-empty"></span></button>');

It triggers the following script (on index.html)

  <script>
          function favButton(atree){
         {% if user.is_authenticated %}
          favTree = Tree.objects.get(pk=atree)
          user.userprofile.tree.add(favTree)
          alert("hearted tree is added to your favourites");
         {% else %}
          alert("please login to heart a tree");
          {% endif %}
          }
      </script>

models.py

class Tree(models.Model):

    treeId = models.IntegerField(primary_key=True)
    neighbourhood = models.CharField(max_length=128, blank=True)
    commonName = models.CharField(max_length=128, blank=True)
    diameter = models.FloatField(null=True, blank=True)
    streetNumber = models.PositiveSmallIntegerField(null=True, blank=True)
    street = models.CharField(max_length=128, blank=True)

    # Populated by sending street address to google and receiving lat lon output
    lat = models.FloatField(null=True, blank=True)
    lon = models.FloatField(null=True, blank=True)

    def save(self, *args, **kwargs):
                self.slug = slugify(self.treeId)
                super(Tree, self).save(*args, **kwargs)

    def __unicode__(self):
        return str(self.treeId)

class UserProfile(models.Model):
    # This line is required. Links UserProfile to a User model instance.
    user = models.OneToOneField(User)




    # The additional attributes we wish to include for a user.
    website = models.URLField(blank=True)
    picture = models.ImageField(upload_to='profile_images', blank=True)

    # Tree field is used to store user's favourite trees
    tree = models.ManyToManyField(Tree, blank=True)


    def __unicode__(self):
        return self.user.username

The atree parameter grabs the treeID which is the object's primary key - I know this part is working as I have tested it with an alert. It is the next few lines of code that do not run and I think this is the crux of my problem:

favTree = Tree.objects.get(pk=atree)
user.userprofile.tree.add(favTree)

What I am trying to do is grab the tree object and add it to the userprofile's tree (many to many) field.

Any insight as to where I should go or what I am doing wrong would be appreciated.

Thanks,

A

0

There are 0 best solutions below