Reputation: 4811
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
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
Reputation: 3272
You can write your own context processor:
Study :
https://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors
http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/
Upvotes: 2