Django: Show Different Content Based On User

I'd like to create a school management system for my personal project.

Let's say there is an Admin for every School. But there is some Admin that can manage more than one schools, and they can switch between schools to manage each school.

I've thought one way to do it, by using different URL path eg.

urlpatterns = [
    url(schools/<int:pk>/, SchoolView.as_view()),

Is there a way so I do not separate by using different URL path for each schools? So, each Admin get similar URL path, but the view render or filter to use different school, based on the Admin.

But I don't really know how to do that? Can I get an advice how to do it. Many thanks!



Every view function accepts a request parameter, so wherever you define your view function it would probably look like:

from django.shortcuts import render

def my_view(request):
    #you can check user here with request.user
    if request.user.is_superuser:
        return render('your_template_for_admin.html', {})
    return render('your_template_for_basic_user.html', {})

EDIT: If you're using a class based view then you can override it's get method like this:

from django.shortcuts import render
from django.views import View

class MyView(View):
    def get(self, request, *args, **kwargs):
        #here you can access the request object
        return render('template.html', {})

Edit based on comment: You can use get_context_data() instead of get() as @Daniel Roseman stated in comments.

from django.views import View

class MyView(View):
    def get_context_data(self, **kwargs):
        #example code assuming that we have a relation between schools and admin A
        context = super().get_context_data(**kwargs)
        context['schools'] = School.objects.filter(admin_id=self.request.user__id)
        return context

And then you can use schools queryset in your template.