简体   繁体   中英

How to create a function is views.py so that all the functions inside the views.py can use it

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?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM