user2225970
user2225970

Reputation:

Access to user in django models

Hi i have problem with django python app. Im creating function in model in django - which gives me true or false in template.

Can i get access to logged user in function in model?

Upvotes: 2

Views: 93

Answers (1)

Brent Washburne
Brent Washburne

Reputation: 13148

Your view method (in views.py) should have a "request" parameter. You can pass in the logged user like this:

class MyMethod(models.Model):
    def method(self, user):
        # do something with user
        return result    # true or false

def my_method(request):
    obj = MyModel.all().filter(...).get()
    result = obj.method(request.user)
    # pass "result" to template

If you have a list of objects and you want to pass in the user from the template, you need to put the user into a variable first:

def my_method(request):
    user = request.user
    objects = MyModel.all()
    # pass "user" and "objects" to template

(inside your template):
{% for obj in objects %}{{ obj.method.user||yesno:"yeah,no,maybe" }}{% endfor %}

This uses the yesno tag on your true/false result.

Upvotes: 1

Related Questions