How to Retrieve All Users of the Default User Model in Django 


               


How to Retrieve All Users of the Default User Model in Django



Python


In this article, we show how to retrieve all users of the default user model in Django.

We are not talking about retrieving users from a custom user model, but the built-in default user model in Django.

So if we have users using Django's built-in default user model, we can retrieve these users in our views.py file using the following code, shown below.



So we have to first import render, so that we can render the template, home.html, in the Blog directory.

The line, from django.contrib.auth import get_user_model, allows us to import the User class. This imports the class that contains all of the users in the Django default user model.

We thn define our view-based function, which we call showthis().

We then create a variable called all_users and set this equal to get_user_model().objects.all()

What this line of code does is it gets all of the objects in the user model and stores them in the all_users variable.

We then pass this all_users variable into the context dictionary.

We then pass this variable into the home.html page through the context dictionary.

We won't go into the home.html template page, because more than likely you already know how to render out a variable from the views.py file into the template file. If you don't, all you have to do is put the variable name in between double curly braces ( {{ variable_name }}). In this case, the statement would be, {{ all_users }} to render out all users in the user model.

And this is all that is needed to retrieve all users of the built-in default user model in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...