I am trying to query data from database using Python shell. settings.py includes:
import django
django.setup()
...
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'products.apps.ProductsConfig',
'users.apps.UsersConfig',
'crispy_forms',
]
When i open Python shell i do:
> from django.conf import settings
> settings.configure()
Then I try to import models:
> from products.models import Product
However, Python returns:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I tried adding django.setup() call in settings and also moving this statement after INSTALLED_APPS.
EDIT: With django.setup() I get the following error when I try to run command runserver:
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
As you noticed, django hasn't been properly initialized and so you are getting this message.
As #davit-tovmasyan mentioned, there is a built in manage.py command to open a django shell in the correct context:
./manage.py shell
Additionally, if you install django-extensions there is a very helpful command which imports all your models, plus common imports:
$ ./manage.py shell_plus
# Shell Plus Model Imports
from django.contrib.admin.models import LogEntry
from project.my_app.models import Model1, Model2
# ...etc, for all django and project apps
# Shell Plus Django Imports
from django.core.cache import cache
from django.conf import settings
# ...
>>> type your python here
If you want to run your own script, for example in temp.py, then you can copy the manage.py code into a new file and run it directly:
import os
import django
# these must be before any other imports of django app code/models
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
django.setup()
from my_app.models import Product
print(Product.objects.all())
# at the command line:
$> chmod +x temp.py
$> ./tmp.py
Also, with django-extensions run_script, is the scripts folder where you can add simple python scripts with a run() method.
Related
i want to activate my models in my files, my code in terminal:
(env) PS C:\Users\MadYar\Desktop\code.py\learning_log> python manage.py makemigrations learning_logs
error:
No changes detected in app 'learning_logs'
im using django to make a web application and i add models in my settings.py like that:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'learning_logs'
]
i dont know why it sais no changes detected in app 'learning_logs'
add empty __init__.py in learning_logs folder.
check if you have any models.py in learning_logs folder.
add some models, which inherited from django.models.Model:
from django import models
class MyModel(models.Model):
myfield = models.Charfield(max_length=255)
call python manage.py makemigrations learning_logs
if you see No changes detected in app 'learning_logs' again, try to read the tutorial, especially this part: https://docs.djangoproject.com/en/4.0/intro/tutorial02/
i'm a newbie to Django and i just started this project....
After Creating Superuser using this command python manage.py createsuperuser I tried to access the admin route but on typing the /admin on the browser it's displays this error on the browser
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/login
Using the URLconf defined in myblog.urls, Django tried these URL patterns, in this order:
1. admin/
I tried adding: LOGIN_REDIRECT_URL = '/admin/' in the settings.py as someone suggested on stackoverflow but it shows the same thing.
Kindly direct me on what i'm not doing right
You need to run:
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
Check if you have on settings:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles'
Your apps
]
And in your URLs from the app:
urlpatterns = [
#
path('admin/', admin.site.urls)
Your apps urls
]
I finally got it right
I started the project from beginning but i made slight changes I did the following:
Created a new folder for my project
cd into the folder
Run python -m venv name-of-virtual-env
cd into name-of-virtual-env
cd into Scripts
Run activate.bat
cd ../../
The name of the virtual environment will appear inside bracket near your directory name, indicating that you've activated your Virtualenv.
Then you start your project.... using
django-admin startproject (name of the project)
I get this error when I add a something to the text field.I'm trying to create a project where someone can enter random messages.
OperationalError at /admin/submit/submit/add/
no such table: main.auth_user__old
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/submit/submit/add/
Django Version: 2.1
Exception Type: OperationalError
Exception Value:
no such table: main.auth_user__old
Exception Location: D:\Anaconda1\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 296
Python Executable: D:\Anaconda1\python.exe
Python Version: 3.8.3
Python Path:
['D:\\PyProjects\\Website',
'D:\\Anaconda1\\python38.zip',
'D:\\Anaconda1\\DLLs',
'D:\\Anaconda1\\lib',
'D:\\Anaconda1',
'C:\\Users\\heman\\AppData\\Roaming\\Python\\Python38\\site-packages',
'D:\\Anaconda1\\lib\\site-packages',
'D:\\Anaconda1\\lib\\site-packages\\win32',
'D:\\Anaconda1\\lib\\site-packages\\win32\\lib',
'D:\\Anaconda1\\lib\\site-packages\\Pythonwin']
Server time: Mon, 5 Oct 2020 17:19:26 +000
This is my models.py
from django.db import models
# Create your models here.
class Submit(models.Model):
title = models.TextField(max_length=140, default='SOME STRING')
status = models.TextField(max_length=140, default='SOME STRING')
description = models.TextField(max_length=140, default='SOME STRING')
Here is my setting.py installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'submit.apps.SubmitConfig',
]
Here is my apps.py
from django.apps import AppConfig
class SubmitConfig(AppConfig):
name = 'submit'
Here is my admin.py
from django.contrib import admin
from .models import Submit
# Register your models here.
admin.site.register(Submit)
I also ran python manage.py makemigrations
and python manage.py migrate
Please help me...Thanks in advance
This seems to work for me..
the original answer:
https://stackoverflow.com/a/59349457/13732795
But I'll copy paste it here too
Go to the virtual environment and install django#2.1.7
pip install django==2.1.7
Delete the db.sqlite3 file in your root folder.
Create the new db.sqlite3 in your root folder.
Re-run migrations:
python manage.py makemigrations
python manage.py migrate
I have below django-program--- walk.py
from django.db import models
from django_fsm import transition, FSMIntegerField
from django_fsm import FSMField, transition
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
import django
django.setup()
from django.core.management import call_command
class Order(models.Model):
STATUS_GO = 0
STATUS_COME =1
STATUS_CHOICES = (
(STATUS_GO, 'GO'),
(STATUS_COME,'come')
)
product = models.CharField(max_length=200)
status = FSMIntegerField(choices=STATUS_CHOICES, default=STATUS_GO, protected=True)
#transition(field=status, source=[STATUS_GO], target=STATUS_COME)
def walk(self):
print("Target moved")
Above code is available in c:\Hello folder.
I have referred few blogs & link for creating new django project.
so in cmd window, dragged to above folder by "cd c:\Hello" & executed:
django-admin startproject mysite
And moved walk.py into mysite folder
And the directory as :
Hello/
mysite/
manage.py
walk.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
And Later executed:
python manage.py migrate
python manage.py runserver
Post which i have been stuck now & confused above two steps is required for my project.
Do
python manage.py startapp polls
is mandate to run now ? If so, what to edit in polls/models.py file ??
Later what do i need to mention in INSTALLED_APPS = [] ???
And keep moving further, where do i place my project walk.py in above directory ?
Now when i run the walk.py , i could see below issue now:
RuntimeError: Model class main.Order doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
Pls any help
In INSTALLED_APPS you will have to add the new app like this:
INSTALLED_APPS = [
// ...
'django.contrib.staticfiles',
'django.contrib.sites',
'polls'
]
Now Django will be aware of your app.
Actual error :
RuntimeError: Model class main.Tag doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
my Solution:
run
django-admin startproject mysite
in the project folder
Hello/
mysite/
manage.py
walk.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
Later added ' main' in INSTALLED_APPS & works fine now
I am making a reusable Django app without a project. This is the directory structure:
/
/myapp/
/myapp/models.py
/myapp/migrations/
/myapp/migrations/__init__.py
When I run django-admin makemigrations I get the following error:
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Obviously, this is because I don't have a settings module configured, because this is a reusable app. However, I would still like to ship migrations with my app. How can I make them?
Actually, you don't need to have project, all you need is settings file and script, that runs migrations creation.
Settings must contain folowing (minimum):
# test_settings.py
DEBUG = True
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'your_app'
]
And the script, that makes migrations should look like this:
# make_migrations.py
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
from django.core.management import execute_from_command_line
args = sys.argv + ["makemigrations", "your_app"]
execute_from_command_line(args)
and you should run it by python make_migrations.py. Hope it helps someone!
You need a functional Django project (with your app installed in it) to make migrations.
A common way to do this is to have a "test" project which contains the bare necessities of a Django project, that you can run to make migrations etc. The migrations will be created in the right place inside your app directory so you can still have proper version control etc within your own reusable app.
The migrations created in this way will be self-contained (assuming your models don't depend on models from other apps) and can be shipped as part of your packaged, reusable app.
Many of the larger Django-based projects actually ship a test project as part of their code, so that developers can quickly get it running in order to test apps and make migrations etc.
Create your_app/migrations_settings.py file:
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'your_app'
]
then
export DJANGO_SETTINGS_MODULE=yourapp.migrations_settings
django-admin makemigrations yourapp
Real Python has a tutorial on writting a reusable Django App.
The chapter Bootstrapping Django Outside of a Project has a very interesting example:
#!/usr/bin/env python
# boot_django.py
"""
This file sets up and configures Django. It's used by scripts that need to
execute as if running in a Django server.
"""
import os
import django
from django.conf import settings
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "your_app"))
def boot_django():
settings.configure(
BASE_DIR=BASE_DIR,
DEBUG=True,
DATABASES={
"default":{
"ENGINE":"django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
}
},
INSTALLED_APPS=(
"django.contrib.auth",
"django.contrib.contenttypes",
"your_app",
),
TIME_ZONE="UTC",
USE_TZ=True,
)
django.setup()
And then:
#!/usr/bin/env python
# makemigrations.py
from django.core.management import call_command
from boot_django import boot_django
boot_django()
call_command("makemigrations", "your_app")