cool breeze
cool breeze

Reputation: 4811

How would you setup a "context" type object in django

In Rails if I want to setup a "context" which is basically objects that every view will need like the user object for a logged in user, or say a store/account/location object, how would I have this available on every view in the django framework?

In Rails I would do something like this:

class BaseController
  before_action :setup_context


  def setup_user
   @user = # load user from db
   @location = # load location for user
  end
end

class HomeController < BaseController

  def index
    # I now can use the variables @user and @location
  end

end

Does Django have these types of events that I can load objects and use them in all my views?

Upvotes: 1

Views: 724

Answers (2)

Ben P
Ben P

Reputation: 115

If I understand your question correctly, I think you're trying to do something like this. I'm still fairly inexperienced with Django myself, so take this with a grain of salt.

Basic example:

views.py

from django.shortcuts import render
from exampleapp.models import User  # User object defined in your models.py

def index(request):
    context = { 'users': User.objects.all() }
    return render(request, 'exampleapp/example.html', context)

example.html

{% if users %}
    {% for user in users %}
        <p>{{ user.name }}</p>
    {% endfor %}
{% else %}
    <p>No users.</p>
{% endif %}

My apologies if I've missed the mark on your question.

Upvotes: 1

Related Questions