Reputation: 789
Hi I have the following definition
if GroupProfile.objects.filter(id=self.request.session['ACL_gid'], permissions__codename='view_page'):
context['can_view_page'] = 1
else:
context['can_view_page'] = 0
return context
I am using this part of code in many of my views. How can I define it once so that I dont need to use it every time?
Upvotes: 0
Views: 3055
Reputation: 445
You can simply write function in any common file like,
def your_func(args):
#do your work
and simply import it wherever you want to use it like a normal python function.
eg. from common import your_func
Upvotes: 4
Reputation: 174718
You need to create a custom template context processor, and then add it to your TEMPLATES
setting. The context provider is something very simple:
from .models import GroupProfile
def view_page(request):
if GroupProfile.objects.filter(id=self.request.session['ACL_gid'],
permissions__codename='view_page').count():
return {'can_view_page': 1}
return {'can_view_page': 0 }
Save this file somewhere; ideally inside an app (the same place where you have the models.py
file) and then add it to your TEMPLATES
setting, make sure you don't override the defaults.
Once you set this up, then all your templates will have a {{ can_view_page }}
variable; and you don't have to keep repeating code in your views.
Upvotes: 0
Reputation: 4606
a) You can create your a method inside your model or in Modelmanager(I think it would be most elegant solution):
class MyManager(models.Manager):
def can_view_page(self, acl_gid, perm_code = 'view_page'):
return 1 if self.filter(id=acl_gid, permissions__codename=perm_code) else 0
class GroupProfile(models.Model):
.....
objects = MyManager()
b) You can create just a function in something like utils.py. c) You can create a Mixin class and put there this function. You can always do there something like:
class MyMixin(object):
def get_context_data(self, **kwargs):
context = super(MyMixin, self).get_context_data(**kwargs)
context['can_view_page'] = 1 GroupProfile.objects.filter(id=self.request.session['ACL_gid'], permissions__codename='view_page') else 0
return context
But I'm not a big fan of this approach since it overrides
instead of extend
- it isn't really transparent in my opinion.
d) You can create a decorator!) But I don't think it is very right case to use it.
Upvotes: 0