Not able to modify DataBase with django - python

I am new to django. Want to create tables in the Database of my project, so I searched the tutorial.
models.py:
from django.db import models
class Blah(models.Model):
first = models.IntegerField()
second = models.IntegerField()
Script to write data into db:
from django.conf import settings
settings.configure()
from core.models import Blah
b = Blah(first = 1, second = 2)
b.save()
When I am trying to launch the script with django 1.9, it gives me the error:
C:\Python27\Scripts\reports>to_db.py
Traceback (most recent call last):
File "C:\Python27\Scripts\reports\to_db.py", line 4, in <module>
from core.models import Blah
File "C:\Python27\Scripts\reports\core\models.py", line 5, in <module>
class Blah(models.Model):
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 94, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Python27\lib\site-packages\django\apps\registry.py", line 239, in get_containing_app_config
self.check_apps_ready()
File "C:\Python27\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I have already added the app to INSTALLED_APPS and I am able to do the exact same commands with "manage.py shell", but not with the script.
What am I missing here?
Thanks

If you do need to script against Django (and the ORM), you'll want to use the shell admin command, passing your script as input to it. Related question

Related

How to properly do monkey Patching on Django 3.1

i'm currently coding a web application with django 3.0 and trying to override some functions of an installed django apps (Python social auth module). I want to do it because i want to change the default behavior.
I have found some method to perform overriding of a module (monkey patching) and try to implement it but i the following errors when i try to implement it :
File "/Users/***********/code/recrutlocataire/recrutlocataire/core/__init__.py", line 1, in <module>
import core.monkey
File "/Users/***********/code/recrutlocataire/recrutlocataire/core/monkey.py", line 6, in <module>
from django.contrib.sessions.models import Session
File "/usr/local/lib/python3.8/site-packages/django/contrib/sessions/models.py", line 1, in <module>
from django.contrib.sessions.base_session import (
File "/usr/local/lib/python3.8/site-packages/django/contrib/sessions/base_session.py", line 26, in <module>
class AbstractBaseSession(models.Model):
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 107, in __new__
app_config = apps.get_containing_app_config(module)
File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config
self.check_apps_ready()
File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 135, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
Create my patch in the monkey.py file in my application directory:
core/monkey.py
from social_core import utils
from social_core.exceptions import InvalidEmail
from django.core import signing
from django.core.signing import BadSignature
from django.contrib.sessions.models import Session
from django.conf import settings
def partial_pipeline_data(backend, user=None, *args, **kwargs):
pass
Import the monkey file in the init file located in my application directory :
core/init.py
import core.monkey
It seems that I have this error because I'm trying to import the session module whereas the application loading is not done but i cannot find a proper way to do it.
Could someone tell me how can I perform it properly please ?

Atom `script` add-on doesn't recognize Django Model/settings when running a script

It seems I run into some dependencies issues when trying to run a python script within my Django based web application using the atom add-on script.
I would like to run the following script using the Atom script add-on:
feeder.py:
import zmq
import time
from time import sleep
import uuid
from models import AccountInformation
context = zmq.Context()
zmq_socket = context.socket(zmq.PULL)
zmq_socket.bind("tcp://*:32225")
time.sleep(1)
while True:
try:
msg = zmq_socket.recv_string()
data = msg.split("|")
print(data)
if (data[0] == "account_info"):
version = data[1]
DID = uuid.UUID(data[2])
accountNumber = int(data[3])
broker = data[4]
leverage = data[5]
account_balance = float(data[6])
account_profit = float(data[7])
account_equity = float(data[8])
account_margin = float(data[9])
account_margin_free = float(data[10])
account_margin_level = float(data[11])
account_currency = data[12]
feed = AccountInformation(
version=version,
DID=DID,
accountNumber=accountNumber,
broker=broker,
leverage=leverage,
account_balance=account_balance,
account_pofit=account_profit,
account_equity=account_equity,
account_margin=account_margin,
account_margin_free=account_margin_free,
account_margin_level=account_margin_level,
account_currency=account_currency
)
feed.save()
# Push data to account information table
else:
print("no data")
except zmq.error.Again:
print("\nResource timeout.. please try again.")
sleep(0.000001)
Unfortunately it raises the following error:
Traceback (most recent call last):
File "C:\Users\Jonas Blickle\Desktop\dashex\Dashboard_app\feeder.py", line 5, in <module>
from models import AccountInformation
File "C:\Users\Jonas Blickle\Desktop\dashex\Dashboard_app\models.py", line 7, in <module>
class AccountInformation(models.Model):
File "C:\Program Files\lib\site-packages\django\db\models\base.py", line 103, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Program Files\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config
self.check_apps_ready()
File "C:\Program Files\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready
settings.INSTALLED_APPS
File "C:\Program Files\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__
self._setup(name)
File "C:\Program Files\lib\site-packages\django\conf\__init__.py", line 60, in _setup
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
[Finished in 0.302s]
When I remove the model import everything just runs fine, it just won't populate my DB then since I need the imported model...
How to possibly solve this?
Your models are inside your apps, and your apps are inside your settings (INSTALLED_APPS), so you should configure the django's settings before you can access them.
Just add these before importing your models:
import django
django.setup()
You should also set DJANGO_SETTINGS_MODULE environment varialbe to specify your settings file; or use django.configure if you prefer (docs).

I can not use mulitprocessing in my django project.Why?

Here is my project folder:
\prjname
---\appname
---\---\subappname1
---\---\---\__init.py
---\---\subappname2
---\---\---\__init.py
---\---\view.py
---\---\models.py
---\---\admin.py
---\---\__init__.py
In models.py I defined some model like:
class model1(models.Model) :
name=models.CharField(primary_key=True, max_length=32)
In subappname1.init.py I have some code like:
from appname.models import model1
import multiprocessing
class myclass(Object):
def myfun(self):
res = []
threadargs=[(arg1,arg2),(arg3,arg4)]
pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())
for arg in threadargs:
res.append(pool.apply_async(self.mywork,arg))
pool.close()
pool.join()
for re in res:
re = re.get()
self.myrecord(re)
def mywork(self,arg1,arg2):
#do something
pass
def myrecord(self,re):
model2.object.create(name=re)
I think it is easy to understand. I am trying to do some time-consuming work by multiprocess. However, when I run such code, I got error below:
Process SpawnPoolWorker-2:
Traceback (most recent call last):
File "E:\programfile\python\lib\multiprocessing\process.py", line 249, in _bootstrap
self.run()
File "E:\programfile\python\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "E:\programfile\python\lib\multiprocessing\pool.py", line 108, in worker
task = get()
File "E:\programfile\python\lib\multiprocessing\queues.py", line 345, in get
return _ForkingPickler.loads(res)
File "E:/suilong/workspace/myproject\myappname\subappname1\__init__.py", line 7, in <module>
from myappname.models import models
File "E:/suilong/workspace/myproject\myappname\models.py", line 10, in <module>
class model1(models.Model):
File "E:\programfile\python\lib\site-packages\django\db\models\base.py", line 105, in __new__
app_config = apps.get_containing_app_config(module)
File "E:\programfile\python\lib\site-packages\django\apps\registry.py", line 237, in get_containing_app_config
self.check_apps_ready()
File "E:\programfile\python\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
Here is my information:
OS: windows7
python: python3.6.0
django: 1.10.6
datebase: Slite3
Is there anyone who can help me? Thanks a lot.
You are importing model1 in __init__.py.But donno where you are using it. From django 1.9
All models need to be defined inside an installed application or declare an explicit app_label. Furthermore, it isn’t possible to import them before their application is loaded. In particular, it isn’t possible to import models inside the root package of an application.
But you can do inline import like.
def mywork(self,arg1,arg2):
from appname.models import model1

Django 1.9 django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet

Trying to use django-shopify-sync in a Django 1.9 project. When loading the config for the app it gives me the following error, likely because it's trying to load some models in the config?
Tried moving the the two imports that eventually import models into the ready() function below, but still getting the same error. Culpirt lines 2 and 3 in the following file https://github.com/andresdouglas/django-shopify-sync/blob/master/shopify_sync/apps.py
The error is:
$ python manage.py runserver
Unhandled exception in thread started by <function wrapper at 0x10753e500>
Traceback (most recent call last):
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/apps/config.py", line 116, in create
mod = import_module(mod_path)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/andres/.virtualenvs/[...]/src/shopify-sync/shopify_sync/apps.py", line 2, in <module>
from shopify_sync.handlers import webhook_received_handler
File "/Users/andres/.virtualenvs/[...]/src/shopify-sync/shopify_sync/handlers.py", line 3, in <module>
from .models import (CustomCollection, Customer, Order, Product, Shop,
File "/Users/andres/.virtualenvs/[...]/src/shopify-sync/shopify_sync/models/__init__.py", line 3, in <module>
from .address import Address
File "/Users/andres/.virtualenvs/[...]/src/shopify-sync/shopify_sync/models/address.py", line 6, in <module>
from .base import ShopifyResourceModel
File "/Users/andres/.virtualenvs/[...]/src/shopify-sync/shopify_sync/models/base.py", line 144, in <module>
class ShopifyResourceModel(models.Model):
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/db/models/base.py", line 94, in __new__
app_config = apps.get_containing_app_config(module)
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/apps/registry.py", line 239, in get_containing_app_config
self.check_apps_ready()
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
UPDATE: If I move the following lines (model imports) https://github.com/andresdouglas/django-shopify-sync/blob/master/shopify_sync/handlers.py#L3-L4 to inside get_topic_models it seems to fix the error. But that's kind of dirty, can anyone come up with a better solution?
If you move the following lines (model imports) https://github.com/andresdouglas/django-shopify-sync/blob/master/shopify_sync/handlers.py#L3-L4
from .models import (CustomCollection, Customer, Order, Product, Shop,
SmartCollection)
inside get_topic_models it seems to fix the error. But that's kind of dirty, can anyone come up with a better solution?
It looks like you may have an ordering issue. Make sure your application is in the INSTALLED_APPS tuple after django-shopify-sync. You can find a few more details in the Application registry documentation.
As unsatisfying as an inline import is, you may be stuck with it. I'd suggest moving
from shopify_sync.handlers import webhook_received_handler
from shopify_webhook.signals import webhook_received
into the ready method in apps.py. This will delay the import until the models are ready.
The change I tried is:
diff --git a/shopify_sync/apps.py b/shopify_sync/apps.py
index 663b43b..0bc1fcc 100644
--- a/shopify_sync/apps.py
+++ b/shopify_sync/apps.py
## -1,7 +1,5 ##
from django.apps import AppConfig
-from shopify_sync.handlers import webhook_received_handler
-from shopify_webhook.signals import webhook_received
-
+import importlib
class ShopifySyncConfig(AppConfig):
"""
## -16,5 +14,9 ## class ShopifySyncConfig(AppConfig):
The ready() method is called after Django setup.
"""
+ signals_webhook_received = importlib.import_module('.signals', package='shopify_webhook')
+ handlers_webhook_received_handler = importlib.import_module('.handlers', package='shopify_sync')
+
# Connect shopify_webhook's webhook_received signal to our synchronisation handler.
- webhook_received.connect(webhook_received_handler, dispatch_uid = 'shopify_sync_webhook_received_handler')
+ signals_webhook_received.webhook_received.connect(handlers_webhook_received_handler.webhook_received_handler, dispatch_uid = 'shopify_sync_webhook_received_handler')
+

Can't import django.db.models from Python GUI

Whenever I type this command in Python GUI:
from django.db import models
it gives me an error like this
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
from django.db import models
File "C:\Python27\lib\site-packages\django\db\models\__init__.py", line 5, in <module>
from django.db.models.query import Q
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 17, in <module>
from django.db.models.deletion import Collector
File "C:\Python27\lib\site-packages\django\db\models\deletion.py", line 4, in <module>
from django.db.models import signals, sql
File "C:\Python27\lib\site-packages\django\db\models\sql\__init__.py", line 4, in <module>
from django.db.models.sql.subqueries import *
File "C:\Python27\lib\site-packages\django\db\models\sql\subqueries.py", line 12, in <module>
from django.db.models.sql.query import Query
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 22, in <module>
from django.db.models.sql import aggregates as base_aggregates_module
File "C:\Python27\lib\site-packages\django\db\models\sql\aggregates.py", line 9, in <module>
ordinal_aggregate_field = IntegerField()
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 116, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 54, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 47, in _setup
% (desc, ENVIRONMENT_VARIABLE))
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.
What can it be the problem? I have django in directory C:\Python27\Lib\site-packages\django\db and in there i have a file called models.
This is the pic
Bizarre isn't it?
Not all of Django supports simply being loaded as a Python module, unfortunately; you need to use the means provided by Django itself to bootstrap the environment needed to load stuff like models.
One option is to use the Django shell but it's also possible to use a purely programmatic solution from your own code. See https://docs.djangoproject.com/en/dev/topics/settings/ for all the options.
Here's also an example by somebody else https://gist.github.com/jordanorelli/1025419 but I haven't verified if it's up to date.
The answer is in the error message:
You must either define the environment variable DJANGO_SETTINGS_MODULE or...
For this reason Django provides a shortcut to loading a python shell with Django settings configured:
https://docs.djangoproject.com/en/dev/ref/django-admin/#shell

Categories

Resources