Arjun Shahi
Arjun Shahi

Reputation: 7330

How to make global context variable in django

here i have some dynamic logo and image.I want to apply them in all the view but for that i have to pass site_data context to each view and it isp very time consuming.So isn't there any solutions so that i can pass site_data context to all the view at one time

models.py

class SiteSetting(models.Model):
    background_image = models.ImageField(upload_to='Background Image',default='NoImageFound.jpg')
    logo = models.ImageField(upload_to='logo',default='NoImageFound.jpg')

views.py

def view_student(request):
    students = Student.objects.all().order_by('-date')
    site_data = SiteSetting.objects.all().order_by('-date').first()
    return render(request, 'admin/view_students.html', {'students': students, 'site_data':site_data,'title': 'All Students'})

template

    <link rel="icon" href="{{site_data.logo.url}}">

Upvotes: 2

Views: 750

Answers (1)

Aman Garg
Aman Garg

Reputation: 2547

You can use context_processor

context_processors.py

from .models import SiteSetting

def get_site_data(request):
    site_data = SiteSetting.objects.all().order_by('-date')
    return {"site_data": site_data}

Add this context processor in your settings.py.

TEMPLATES = [
    {
        ....
            'context_processors': [
                ...
                'path.to.context_processors.get_site_data',

            ],
        },
    },
]

Upvotes: 5

Related Questions