4

I'm trying to implement some customize login through the custom methods in Django's models. I want to know if its possible to:

  • Get request.user in a custom method
  • Get the user that made the request in the method
  • Or pass an argument to the custom method

Thinking in doing something like this:

class OneModel(models.Model):
    (...)

    def viewed(self):
        profile = request.user.profile
        viewed = self.viewed_episodes.filter(user=profile).exists()
        if viewed: return True
        else: return None

Another possibility that came to my mind is this:

class OneModel(models.Model):
    (...)

    def viewed(self, user):
        profile = user.profile
        viewed = self.viewed_episodes.filter(user=profile).exists()
        if viewed: return True
        else: return None

But I think neither of this are possible. Maybe what I need is a template tag?

1 Answer 1

5

Second one is correct.

def viewed(self, user):
    return self.viewed_episodes.filter(user=user.profile).exists() or None
Sign up to request clarification or add additional context in comments.

4 Comments

OK, but then how do I pass the user in the template? Something like {{ instance.viewed user=request.user }} ?? It doesn't work (Error: Could not parse the remainder)
@anders You should do it in your view, it takes request as a first argument.
OK, I asked wrong then... It should be "Or pass an argument to the custom method in the template"
@anders Both ways are good. If you want it only for display, you should write a template tag.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.