Search code examples
pythondjangoconsole

How do they run these commands in python console within Django project?


How do they run these python commands in python console within their django project. Here is example.

I'm using Windows 10, PyCharm and python 3.7. I know how to run the project. But when I run the project, - console opens, which gives regular input/output for the project running. When I open python console - I can run commands, so that they execute immidiately, but how do I run python console, so that I can type some commands and they would execute immediately, but that would happen within some project?

Example from here:

# Import the models we created from our "news" app
>>> from news.models import Article, Reporter

# No reporters are in the system yet.
>>> Reporter.objects.all()
<QuerySet []>

# Create a new Reporter.
>>> r = Reporter(full_name='John Smith')

# Save the object into the database. You have to call save() explicitly.
>>> r.save()

# Now it has an ID.
>>> r.id
1

Solution

  • When you run the project you're using a management command: python manage.py runserver. To enter a console that has access to all your Django apps, the ORM, etc., use another management command: python manage.py shell. That will allow you to import models as shown in your example.

    As an additional tip, consider installing the Django extensions package, which includes a management command shell_plus. It's helpful, especially (but not only) in development, as it imports all your models, along with some other handy tools.