Filter posts for groups leaders

I want to filter posts visibility:

  1. if user is website admin show him all posts
  2. if user is group leader show him posts from only his group
  3. if user is not website admin or group leader show him only his posts

views.py:

def index(request):
    if not request.user.is_authenticated:
        return redirect('loginUser')
    else:
        forrents = ForRent.objects.none()
        if request.user.is_superuser:
            forrents = ForRent.objects.order_by('-id')
        elif request.user.groups.filter(name='leader').exists():
            group = request.user.groups.filter(name='leader').first()
            forrents = forrents.filter(group=group)
        else:
            forrents = forrents.filter(author=request.user)

        context = {
            'forrents': forrents,
        }
        return render(request, 'index.html', context)

models.py:

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class UserGroup(models.Model):
    name = models.CharField(max_length=100)  
    leader = models.ForeignKey(User, on_delete=models.CASCADE, related_name='led_groups')
    members = models.ManyToManyField(User, related_name='user_groups')
    def __str__(self):
        return self.name

class ForRent(models.Model):
    mobile = models.IntegerField()
    myhomelink = models.URLField()
    myhomeid = models.IntegerField()
    sslink = models.URLField()
    ssid = models.IntegerField()
    area = models.IntegerField()
    price = models.IntegerField()
    address = models.TextField()
    limitations = models.TextField()
    agent = models.TextField()
    group = models.ForeignKey(UserGroup, on_delete=models.CASCADE, related_name='rent_ads', blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rent_posts')
    def save(self, *args, **kwargs):
        if not self.group:
            self.group = self.author.user_groups.first()
        super().save(*args, **kwargs)

It looks like you’ve already written the code you want.

But it seems like you want your code to be more concise.

from django.contrib.auth.decorators import login_required

@login_required(login_url='loginUser')
def index(request):
  if request.user.is_superuser:
    queryset = ForRent.objects.all()
  elif UserGroup.objects.filter(members=request.user, name='leader').exists():
    # queryset = ForRent.objects.filter(group__name='leader')
    # i think it is better.
    queryset = ForRent.objects.filter(author__user_groups='leader')
  else:
    queryset = ForRent.objects.filter(author=request.user)
  context = {
    'object_list': queryset,
  }
  return render(request, 'index.html', context)
class ForRent(models.Model):
  class Meta:
    ordering = ['-id']
  ...

Hello! Thanks! Just leader is not separate group name. It’s field of UserGroup model. Is it noted in your code?

There may be communication problems because a translator is used.


from django.contrib.auth.decorators import login_required

@login_required(login_url='loginUser')
def index(request):
  if request.user.is_superuser:
    queryset = ForRent.objects.all()
  else:
    group = UserGroup.objects.filter(leader=request.user)
    if group.exists():
      # queryset = ForRent.objects.filter(group__in=group)
      # i think it is better.
      queryset = ForRent.objects.filter(author__user_groups__in=group)
    else:
      queryset = ForRent.objects.filter(author=request.user)
  context = {
    'object_list': queryset,
  }
  return render(request, 'index.html', context)