Search code examples
djangodjango-tables2

Populate table only with users that satisfy a condition?


I have an expanded django.auth.User looking like this:

class ExtendedUser(models.Model):
    user = models.OneToOneField(User)
    is_admin = models.BooleanField()    

This table contains both regular and admin users. If the user has is_admin is True he is redirected to a admin page. On the admin page, he should see a table with all the users that are NOT admins. Stated differently, only users that shows up in the QuerySet:

p = ExtendedUser.objects.get_query_set()
p.filter(is_admin = False)

should be shown in the table.

I'm using django-tables2 for generating the tables in the admin page, however they by default show all the users.

class ExtendedUserTable(tables.Table):
    class Meta:
        model = ExtendedUser

What is the recommended way to render the non admin users only?

Note: The default Django admin doesn't work for me for other reasons.


Solution

  • The solution is to generate a filtered QuerySet and pass it into to the table as content.

    Here is how the view.py looks like:

    from django_tables2 import RequestConfig
    from student_upload.models import ExtendedUser
    from admin.tables import ExtendedUserTable
    
    def index(request):
        p = ExtendedUser.objects.get_query_set()
        table = ExtendedUserTable(p.filter(is_admin = False))
        RequestConfig(request).configure(table)
        return render(request, 'admin/index.html', {'table': table})
    

    The tables.py is unchanged.

    class ExtendedUserTable(tables.Table):
        class Meta:
            model = ExtendedUser