use Django database models externally - python

My site is named ficosa. I have a Django server set up with a sqlite database that contains a table named core_Data. Now, I am developing a python file named serverMQTT.py that should insert data into that sqlite database. This file is outside Django so in order to import the Django models from ficosa site I call django.setup()
import django
from django.conf import settings
from ficosa import settings as fsettings
settings.configure(default_settings=fsettings, DEBUG=True)
django.setup()
Now this script or any imported module can use any part of Django it needs.
from core.models import Data
However, I am having an error:
AttributeError: 'module' object has no attribute 'LOGGING_CONFIG'
I would be gratefull if sombody could help me

That's not how you configure settings in a standalone app. Note what the documentation says:
Be aware that if you do pass in a new default module, it entirely replaces the Django defaults, so you must specify a value for every possible setting that might be used in that code you are importing.
Presumably, your fsettings module only contains database settings. In which case, just override that one thing:
settings.configure(DATABASES=fsettings.DATABASES, DEBUG=True)

Related

Django model access from custom file

Can I receive access to Model from some custom file. For example I create folder in my project with name Bot. Create some custom_file.py, in current file call model from other app.
For example:
from trading.models import Values
Then I get an error:
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.
Also try solution like this in my custom_file.py:
import os
import django
os.environ["DJANGO_SETTINGS_MODULE"] = 'trading.settings'
django.setup()
But still doesn't work.
You don't need to do any fancy stuff from within the file, just create it in your app module (folder) and import any model you want, exactly as in the example you provided.

How do I import Django models into python file?

I have a Django model which stores inputs from a form, now that I have the data stored in Django I need to import those models to a python file.
As per documentation,
If you’re using components of Django “standalone” – for example,
writing a Python script which loads some Django templates and renders
them, or uses the ORM to fetch some data – there’s one more step
you’ll need in addition to configuring settings.
After you’ve either set DJANGO_SETTINGS_MODULE or called configure(),
you’ll need to call django.setup() to load your settings and populate
Django’s application registry. For example:
import django
from django.conf import settings
from myapp import myapp_defaults
settings.configure(default_settings=myapp_defaults, DEBUG=True)
django.setup()
# Now this script or any imported module can use any part of Django it needs.
from myapp import models

Django settings: sharing ORM with a standalone module

Introduction:
I am learning Django as I develop my first project using PyCharm with Python 3.8 and Postgresql.
I have a problem with the settings.
Environment description:
My aim is to have a Django project for a web site connected to a database (let's call it "web_db"), which is fed at regular intervals with data from an external source (another database, let's call it "source_db").
For this ETL process from one database to the other one, I am developing a Python module called "source2web". I read the content of source_db using psycopg2.
I am developing everything inside one PyCharm project.
Now, since I will be using Django ORM to access the content of web_db from the Django application server, I concluded I might as well use Django ORM in source2web to load my content into web_db.
This means I am trying to share some code between the Django project and source2web: the ORM models of Django.
source2web is simply launched as a python module ( python source2web.py).
Inside my PyCharm project, I have a src folder inside which are all my python modules, with a tree like this (folders are noted with parenthesis) :
(src)
|--(project_name)
|--(module1)
| |--source2web.py
|
|--(django)
|--(django_project)
|--(django_project)
|--(another_app)
The folders django_project/django_project and django_project/another_app have been created classicaly by Django with the commands django-admin startproject django_project and python3 manage.py startapp another_app.
The ORM models I want to share are the model classes inside the file django_project/another_app/models.py
The problem:
I tinkered to find a way to use the Django ORM models from source2web. I thought I had it : inside the code of source2web, I added these lines :
os.environ['DJANGO_SETTINGS_MODULE'] = 'project_name.django.django_project.django_project.settings'
import django
django.setup()
But then, I realize that the Django server and the standalone module source2web can both work, but not with the exact same content inside project_name.django.django_project.django_project.settings.py : the name of another_app in the list of INSTALLED_APPS must be different.
Django requires the app to be listed as just another_app
source2web requires the app to be listed as project_name.django.django_project.another_app
I am sure I could find a 'dirty way' to solve this, but I also think I am not the first one to face this problem (sharing Django ORM code between a Django project and a standalone program) and I hope there is cleaner way to manage this.
What I can think of is duplicating the module project_name.django.django_project.django_project.settings and then just change the settings call inside source2web ( os.environ['DJANGO_SETTINGS_MODULE'] = ... ) but I never like duplicating code and maybe there is a cleaner than that ?
I have found at least one decently clean workaround :
In the project_name.django.django_project.django_project.settings file, I have left the value of INSTALLED_APPS that work with Django, i.e., the list of default apps created with the Django Project plus another_app.
Then in the source2web module, I have changed my code for initializing Django ORM :
In module source2web, I added 2 lines :
import project_name.django.django_project.django_project.settings as djangosettings
djangosettings.INSTALLED_APPS = ['project_name.django.django_project.another_app',]
os.environ['DJANGO_SETTINGS_MODULE'] = 'project_name.django.django_project.django_project.settings'
import django`
django.setup()
This way, I leave untouched the settings for the Django server, and only override what's necessary in the source2web module (i.e. the value of INSTALLED_APPS, getting rid at the same time of all the default apps I don't need for my ETL process).
It works and seems robust enough.
Still, it brought me to question the whole project structure :
Because obviously, the whole problem is the result of the PyCharm project considering for source root src/, while the Django project considers for root project_name/django/django_project/ .
There should be a way to reconcile them, but how ?

Python-Django module import issue

I have JSON data coming through various external API's into my Django project. I have two apps, one called 'products' and other 'extract'. Through product app, have created the database and rendered the views required. Objective of extract app is to parse the JSON data and create/update the fields in the Django database. I have this code saved in extract/views.py as shown below -
import json
import urllib2
from products.models import Product
url = " .........."
.............
for i in data[results]:
Product.objects.get_or_create (...........)
The issue I am having is this code is working well in python shell. It is extracting all the JSON data and updating the database. But, when I run the script on the command line outside of Python shell, it is giving error - 'Import error: No module named products.models'.
Django requires you to run python manage.py shell in order for the product app's models and Django internals to be initialized.
Check out this blog post by Stavros Korokithakis to convert your code into a standalone script.
I believe the error is with the directory set up. Make sure all your migrations are done as well as the initial folder has the paths to your apps. Possible you need to include the paths to each app in the other's settings.

Module "mymodule" does not define a "MyBackend" authentication backend

I'm trying to use a custom authentication backend for a Django project I'm working on. My backend is based on the LDAPBackend found in the article LDAP Authentication in Django with Backends.
I'm getting the floowing error when I attempt to log in:
ImproperlyConfigured at /admin/
Module "challenge.backends" does not define a "LDAPBackend" authentication backend
My project is called "challenge". There is a subdirectory, "backends", which contains __init__.py and LDAPBackend.py.
My settings.py is configured to use this backend thusly:
AUTHENTICATION_BACKENDS = (
'challenge.backends.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
I am able to import the module myself using python manage.py shell and then from challenge.backends import LDAPBackend.
I'm not sure what to check now since everything appears to be in the right place.
You are importing it in wrong way. You are importing a module, rather than a class. That's why shell allows you to import it, but django complains.
You should use challenge.backends.LDAPBackend.LDAPBackend.
Also, it's a good idea to stick with PEP8 when naming modules, this way you won't be confused that way again. Modules should be names all in lowcase and without spaces, underscores, etc.

Categories