I have a tree of models defined in my Django app (e.g. ‘a’ is a top level model, which has many ‘b’s, which has many ‘c’s). I also have the Views/Templates that render these appropriately. For each one of these models I typically need to do a Database query based on the current logged in user.
For example, it’s similar to how each user on stack overflow can mark a question with a star. If my model is the question, I would ask the model if the current user has this question starred and then render it appropriate in the template.
My first thought was to try to pass a parameter in the template (which I now know doesnt’ work).
# template
{{ question.is_starred(request.user) }} # Can't work.
My second thought was to have some type of global variable (which I don’t like on principle).
# model
class question (Models.model)
def _is_starred(self):
# Use a global variable to find out the current logged in user!
My third thought was to have the View tell the model the currently logged in user, but the trouble is, I have a tree of model objects and I think I’d have to load and set every model in the tree, even if I don’t end up using them all. I assume that the objects are lazily loaded.
# view
def view_one_question(request, question_id):
q = Question.objects.get(pk=question_id)
q.SetCurrentlyLoggedInUser (request.user.id)
# !!!! But what about the other network of objects that the question has?
return render_to_response(...)
Any advice is appreciated. I’m new to Django and trying to start this project off with the best design possible.
Your first example is the right idea, but the wrong implementation. You can’t pass parameters to methods in Django templates. The easiest way around this is a simple filter:
Then, in your template: