简体   繁体   中英

How do you call a user defined function in views.py DJANGO

The requirement is to display the logged in username and his role in the organization in all the pages at the top right corner. The role can be identified by the permissions he is given.

My approach:

I thought of creating a user-defined function in views.py and call it in each and every other function. The function that I create should check the current user's permissions and based on them his role should be decided. All these details must be sent to base.html so that it will render and display the username and his role every time the page is loaded.

Any suggestions on other approaches are welcomed and if my approach is entirely wrong please let me know.

In the views you could do something like:

context = {
'username': username,
'role': role,
}


return render('template.html', context)

and in template.html you would then render it like:

{username} {role}

You can find your answer in the comments section of: Can I call a view from within another view?

btw, yes you can create a method to validate user/department. below is the sample of how I have done in my app. A better approach I feel is to save such details in DB as a boolean flag and use django admin's capabilities to ease your work.

def validate_details(request): user = request.GET['username'] user_details = User.objects.filter(name=user).values_list("name", "department", flat=True) # Call validation method defined in view is_ok = validate_user(user_details) if is_ok: return render_to_response("main/landing.html", {"user": user_details["name"],"department":user_details["department"]}, context_instance=RequestContext(request)) else: return render_to_response("main/landing.html", {"user":"NA","department":"NA"}, context_instance=RequestContext(request))

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