Home > Mobile >  How to prevent users from seeing all content in Django?
How to prevent users from seeing all content in Django?

Time:12-19

I have a website and I want to prevent visitors to seeing content unless they have permission. How can I restrict them?

CodePudding user response:

I recommend taking a look at Permissions and Authorization in the django docs.

Here is one way of doing this:

In your User model:

class User(AbstractUser):
    @property
    def has_permission_I_want(self):
        # check permissions here
        # return True or False

In a view:

from django.contrib.auth.decorators import user_passes_test
@user_passes_test(user.has_permission_I_want)
def some_view(request)
  # Some code here

Or limiting content within a page, pass user into the template dict from the view:

return render(
            request, "app/some_page.html",
            {"user": request.user}
        )

and in the template:

{% if user.has_permission_I_want %}
<p> You can see this content </p>
{% endif %}

Also checkout this SO question.

CodePudding user response:

If you want to make it so that a user has to log in to access a function, you could

from django.contrib.auth.decorators import login_required
@login_required
def some_view(request):
    # Some code inside the function

Check for permissions without using a decorator:

# models.py
from django.db import models
class UserProfile(models.Model):
    has_permission = False

While registering a user, create a record in UserProfile

# admin.py
from django.contrib import admin
from app.models import UserProfile
admin.register(UserProfile)

And then head over to the admin to set permissions

def some_view(request):
    user_profile = UserProfile.objects.get(id=request.user.pk)
    if userprofile.has_permission:
        # Give permission
    else:
        # Deny permission

Creating a decorator

Create a file, decorators.py in the app

from django.core.exceptions import PermissionDenied
from simple_decorators.apps.models import Entry

def check_if_deleter_is_author(function):
    def wrap(request, *args, **kwargs):
        post = Post.objects.get(pk=kwargs['post_id'])
        if post.created_by == request.user:
            return function(request, *args, **kwargs)
        else:
            raise PermissionDenied
    wrap.__doc__ = function.__doc__
    wrap.__name__ = function.__name__
    return wrap
# views.py
from app.decorators import check_if_deleter_is_author
@check_if_deleter_is_author
def some_view(request):
    # Some code to delete the post
  • Related