1

I'm writing my first Django application in Django 2.0

My application has two types of membership level

  1. Free Users
  2. Paid Users

Also, there in the application I want certain function/views disabled for Free Users and hide elements in template based on the membership level.

How can I manage all these in my application?

Is it possible to do it all using built-in permission manager?

I tried reading the docs, but it contains few inbuilt modules and could not get how to separate it as per my requirement

Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

2 Answers2

3

Yes you can... The easiest way would be the Group-User-Model. you can use the built-in user and group management. Simply great a group free and paid and add the user in that group. You can query in every function like

def main(request):
  if request.user.groups.filter(name='paid').exists():
     return HttpResponse("You're a paid user")
  else:
     return HttpResponse("You're a free user")

or if conent only visible for paid users:

def onlyPaidUsersView(request):
  if request.user.groups.filter(name='paid').exists():
     return render(request, 'paid.html',{})
  else:
     return HttpResponse("Only available for paid users",status=403)

And as well in template files - you just need to define your own templatetags:

from django import template
from django.contrib.auth.models import Group

register = template.Library()

@register.filter(name='has_group')
def has_group(user, group_name):
    group =  Group.objects.get(name=group_name)
    return group in user.groups.all()
nrhode
  • 913
  • 1
  • 9
  • 27
  • Thanks. Is there a way (*preferably decorator*) to restrict `CreateView` to the paid user only? or some sort of permission **can_add** – Anuj TBE Dec 28 '17 at 08:55
  • Yes there are a few options in the built-in system. Simply login to the `/admin` dashboard and edit the group. There are already some permissions on core level and on model level... – nrhode Dec 28 '17 at 08:59
  • I want to check it on view level like in view check if user/group has permission to create else print message and reload same page or redirect – Anuj TBE Dec 28 '17 at 09:01
2

Need to answer here for code formation:

sure, simply add your own template tag like mentioned here:

https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/

and add something like:

@register.filter(name='has_perm')
def user_has_perm(user, perm):
if request.user.has_perm('app_name.%s'%perm):
   return True
else:
  return False

and in the html-file:

{% load myfilter %}
{% if request.user|user_has_perm:'can_add_sth' %}
...
{% else %}
...
{% endif %}
nrhode
  • 913
  • 1
  • 9
  • 27