"I only need to run a part of this code, is there any way?"
Yes, it is possible to execute a snippet of code or script using Django Shell. It is an interactive command-line interface that allows us to interact directly with the database and test snippets of code. It's like the Python prompt, but with the possibility of importing functions, models, etc. from your project.
This command opens the prompt with the Django settings already imported, so it allows you to work directly from the root folder of a Django project.
python manage.py shell
And now we can use functions, models, etc.
However, I will show you how to run a .py file directly in this console. To do this, we will create a script to create mocked users.
1) Create a file at the same folder level as manage.py (the name is of your choice)
touch shell.py
2) In the shell.py file, import the user model
from django.contrib.auth.models import User
3) Define number of users to be created
QNT_USERS = 10
4) Implement the following code to create mocked users
for index in range(QNT_USERS): user = User.objects.create( username=f"user_{index}" ) user.set_password("padrao@123") user.save()
5) Finally, to run this script just run this command in your terminal:
python manage.py shell < shell.py
The above is the detailed content of Django: How to use the Shell?. For more information, please follow other related articles on the PHP Chinese website!