Search code examples
djangoanalysiswagtail

Create a custom user tacking method on the wagtail?


I have been followed accordbox to create some models. For user activity analysis, I would like to save the user_id, restaurant_id, and time on visited RestaurantPage. The logic is when get_context function in the Restaurant Model, it will use tracking function to save record in TrackUserRestaurant model.

The print function is used to check the request.user.id and restaurant.id.

But I can't get any new record on the TrackUserRestaurant model.

Did I misunderstand something?

I am new to Django and wagtail.

class RestaurantPage(Page)
    .... #other fields
    view_count = models.PositiveIntegerField(default=0,
                                             editable=False)

    @property
    def restaurant_page(self):
        return self.get_parent().specific

    def get_context(self, request, *args, **kwargs):
        context = super(RestaurantPage, self).get_context(request, *args, **kwargs)
        context['restaurant_page'] = self.restaurant_page
        context['restaurant'] = self
        self.tracking(request)
        return context

    def tracking(self, request):
        current_user = request.user
        track = TrackUserRest
        track.user_id = 0
        track.restaurant_id = self.pk
        track.time = timezone.now()
        if request.user.id != None:
            print('user id:' + str(current_user.id))
            track.user = request.user.pk
        print('rest id:' + str(self.pk))
        return track.save(self)
class TrackUserRestaurant(models.Model):
    user_id = models.PositiveIntegerField(null=True)
    restaurant_id = models.PositiveIntegerField(blank=False, null=False)
    time = models.DateTimeField(auto_now=True, auto_now_add=False)

    class Meta:
        ordering = ('time', )

    def __str__(self):
        return 'Restaurant Tracking system: user.id({}) viewed rest.id({}) at timezone.({})'.format(self.user_id,
                                           self.restaurant_id,
                                           self.time)

Solution

    1. The names used in your tracking method (TrackUserRest, rest) do not match your class definition (TrackUserRestaurant, restaurant_id)
    2. The line track = TrackUserRest does not create a TrackUserRest object - it needs to be track = TrackUserRest(). As a result of this, the following lines are setting attributes on the TrackUserRest class, not a TrackUserRest object.
    3. With this fixed, track.save(self) should become track.save().