1

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?

cool breeze
  • 4,461
  • 5
  • 38
  • 67
  • Is it only `user` that you need to access? If so then `request.user` is the object to access for view methods. – Shang Wang Jun 14 '16 at 17:56
  • @ShangWang no not user, I usually do: context.user context.location context.account i.e. everything added to a context object. – cool breeze Jun 14 '16 at 18:10
  • 1
    This is what context processors are for, see for instance http://stackoverflow.com/questions/2893724/creating-my-own-context-processor-in-django or http://stackoverflow.com/questions/2246725/django-template-context-processors - specifically that's how Django adds the `user` object to the request, and you can write your own if you need more than the built in ones provide. – Peter DeGlopper Jun 14 '16 at 18:12

2 Answers2

2

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/

abhinsit
  • 3,214
  • 4
  • 21
  • 26
1

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.

Ben P
  • 115
  • 9