[Answer]-Get request.user object

1đź‘Ť

I think you just need M2M field for votes. Something like this:

class Event(models.Model):
    description = models.TextField()
    author = models.ForeignKey(User)
    voted_users = models.ManyToManyField(User, related_name='voted_events')

Then you can use it:

request.user.voted_events.all()

or

if specified_event in request.user.voted_events:
    print "%s up voted by %s" % (specified_event.description, request.user.username)

Your has_upvoted() method is not good idea.

0đź‘Ť

Yes, but this is not very nice, please see it:

https://djangosnippets.org/snippets/2179/

I don’t know another way

👤Goin

0đź‘Ť

Models can be used outside the http request / response cycle (management commands etc) so you cannot assume there’s a globally available request object. The only clean way to make “the current request.user” available to you model’s methods is to explicitly pass it as argument. This will also make your code more testable and more robust.

class Event(models.Model):
   description = models.TextField()
   author = models.ForeignKey(User)

   # strange naming... looks like a predicate
   # but acts as a getter ???

   def has_upvoted(self, user):
      return Up.objects.filter(
          user=self.request.user,
          event=self.id)

Then in your view:

def whatever(request, ...):
    event = get_your_event(...)
    ups = event.has_upvoted(request.user)

If you need a direct access from templates you’ll have to wrap the call in a custom template tag or filter, depending on what has_upvoted is really supposed to be (predicate or accessor)

the templatetag version:

# yourapp/templatags/whatever.py
@register.assignement_tag
def has_upvoted(event, user):
    return event.has_upvoted(user)

and then

# yourtemplates/whatever.html

{% has_upvoted evt request.user as whatever %}
{{ whatever }}

more about custom tags and filters here: https://docs.djangoproject.com/en/1.6/howto/custom-template-tags/

Leave a comment