Django-crontab can't make model query - django

I have a model inside tools app called ApiKeys and tried to update the model in specific time intervels. I used django-crontab for this purpose.
CRONJOBS = [
('*/1 * * * *', 'tools.cron.reset_api_calls','>>logs.log')
]
function -
from .models import ApiKeys
def reset_api_calls():
try:
keys = ApiKeys.objects.all()
for key in keys:
key.api_calls = 0
key.save()
except Exception as e:
print(e)
model -
class ApiKeys(models.Model):
key_token = models.CharField(max_length=50, primary_key=True)
api_calls = models.IntegerField(default=0)
las_used_date = models.DateTimeField(default=timezone.now)
But it gives error log - no such table: tools_apikeys
Note: The table does exist in database and accessible through django-shell and views.py as well.

It doesn't work that way, as you need to setup Django for these command to work
You have 2 options
Implement this as a management command
Setup Django manually as the start of your script.
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
django.setup()

You should update your DATABASES settings in main project from:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
to:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
by adding os.path.join you can specify directory from which system should take a database, because initially it will look for db.sqlite3 in other pwd.

Related

How to connect SQLlite to a project in Django (not an app)

While creating the project I didn't create an app and did everything in the base project. Now I am trying to connect database to my base project(not the app)
I tried 'python manage.py makemigrations' but its showing "No changes detected".
I even tried adding my project to INSTALLED_APPS in settings.py and then trying 'python manage.py makemigrations ' but it is showing an error " for model in model_or_iterable:
TypeError: 'type' object is not iterable "
I have created two models
from django.db import models
class studentlogin(models.Model):
stu_name =
models.CharField(max_length=30,default='',null=False)
stu_email =
models.EmailField(max_length=20,default='',null=False)
stu_password =
models.SlugField(max_length=15,default='',null=False)
class facultylogin():
fac_name =
models.CharField(max_length=30,default='',null=False)
fac_email =
models.EmailField(max_length=20,default='',null=False)
fac_password =
models.SlugField(max_length=15,default='',null=False)
also registered the models in admin.py
'admin.site.register(studentlogin), admin.site.register(facultylogin)
I need help !!
You will need to set up sqlite3 in the same file that you have INSTALLED_APPS by using the DATABASES = {} setting
For example:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
Example
Might be a duplicate
Example2

How to configure sqlite of django project with pythonanywhere

I have deployed my project to pythonanywhere.
It is working locally.
But with pythonanywhere I am getting no such table exception.
I have configured sqllite as in this link
Just mentioned to generate the sqlite file using runmigrations.
I have changed the settings.py to use os.path.join at that Database section also but still same issue.
Exception Type: ProgrammingError
Exception Value:
(1146, "Table 'todo_todo' doesn't exist")
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
tried with os.path.join also but same error.
my models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Todo(models.Model):
title = models.CharField(max_length=100)
memo = models.TextField(blank=True)
created=models.DateTimeField(auto_now_add=True)
datecompleted=models.DateTimeField(null=True, blank=True)
important=models.BooleanField(default=False)
user = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.title
I migrated individual apps also.
python manage.py makemigrations appname

Concurrency issue? Standalone python script sharing settings.py and ORM with django server has unreliable view of DB objects?

I'm having a strange problem that is difficult to reproduce (everything worked 2 days ago but some time between then and now no longer does--with no changes in the interim!)
I have a django server program which we are running via gunicorn with multiple worker subprocesses and a separate small REST webservice which shares the settings.py of the server program and acts on the same DB objects. The code for this server program is roughly as follows:
# my app's models.py
class TestConfig(models.Model):
## various attributes
class Test(models.Model):
## some attributes
def startTest(self):
return TestExecution.objects.create(test=self)
class TestExecution(models.Model):
test = models.ForeignKey(
Test,
on_delete=models.CASCADE
)
config = models.ForeignKey(
TestConfig,
on_delete=models.CASCADE,
null=True
)
# excerpt from a post() method in my app's views.py
test = Test.objects.get(test_id)
if config_form.is_valid():
config = config_form.save()
config_id = config.id
test_exe = test.startTest()
test_exe.config = config
test_exe.save()
webservice_response = requests.get(
'http://{}:{}/rest/add_to_queue/{}'.format(
webservice_ip, webservice_port, test_exe.id))
The other program (small REST webservice) sharing the same settings.py as the django server program looks as follows:
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
import django
django.setup()
# the REST endpoint referenced from the django server program
#app.route('/rest/add_to_queue/<test_exe_object_id>/')
#app.route('/rest/add_to_queue/<test_exe_object_id>')
def add_to_queue(test_exe_object_id):
from myapp.models import TestExecution
try:
exe_object = TestExecution.objects.get(pk=int(test_exe_object_id))
# for completeness the database section of my settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test_db',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}
As I mentioned, this was all working fine a few days ago, then when I tried again today I was getting a DoesNotExist in the second program when trying to "get()" the TestExecution object using its 'id'.

How to connect to my heroku database from localhost?

I'm new in django and trying to connect to my heroku database from my localhosted django app.
I've followed the instructions on heroku website but it's seems django won't understand that i'm trying to access an external database.
i get this error
relation "myAppName_user" does not exist
LINE 1: INSERT INTO "myAppName_user" ("title", "content") VALUES
('Beat...
However i never created or never intented to create a table named myAppName_user
I'm just trying to access the table user in my heroku postgres db but i don't know why it tries with myAppName_user
i just explicitly added myAppName in the INSTALLED_APPS config as django throws an error if it's not the case.
My DATABASE config :
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
DATABASES['default'] =
dj_database_url.config(default='postgres://xxxxx')
I want to test my database from my localhost. I'm doing this easily with Node JS but i can't find the solution in django.
Any suggestions ?
EDIT
from __future__ import unicode_literals
from django.db import models
class Fruits(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.name

TEST Mirror default database but no data

I am trying to set up some testing on my Django application. I have used a database mirror for the test database. When I try to run few test it appears the data from 'default database' is not available in the mirror test database.
'default': { #'sqlite': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'OPTIONS':{
'timeout': 180,
},
# 'TEST':{
# 'MIRROR': 'default',
#
# }
},
'replica': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'OPTIONS':{
'timeout': 180,
},
'TEST_MIRROR': 'default'
}
my tests:
data_school = DataSchool.objects.all()
self.assertTrue(data_school.exists())
I am confused, the test_mirrors configured by the database administrator as a read replica of default database.and in theory any data in default database should be available for test? If I have any configuration errors please do let know. Thanks
This is a known bug in Django:
https://code.djangoproject.com/ticket/23718
The workaround described in that ticket is your best bet. I ran into this same issue and implemented the workaround by defining a custom TestCase class and inheriting from that custom test case in all my tests. I also chose to use setUpClass and tearDownClass instead of setUp and tearDown as described in the bug ticket. Either should work though.
from django.db import connections
class CustomTestCase(TestCase):
#classmethod
def setUpClass(cls):
super(CustomTestCase, cls).setUpClass()
connections['replica']._orig_cursor = connections['replica'].cursor
connections['replica'].cursor = connections['default'].cursor
#classmethod
def tearDownClass(cls):
connections['replica'].cursor = connections['replica']._orig_cursor
super(CustomTestCase, cls).tearDownClass()