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!
Answer
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
#example
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.
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module