How to configure sqlite of django project with pythonanywhere - django

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

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

Django-crontab can't make model query

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.

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

Django 1.9 - JSONField in Models

I'm trying to set up a models file in Django 1.9 using the new JSONField. I have found examples using postgres but none with MySql. In the examples with postgres they do a
from django.contrib.postgres.fields import JSONField
How do I go about importing it for MySql?
Thanks
UPDATE: Django 3.1 now supports JSONField natively for multiple databases: https://docs.djangoproject.com/en/dev/releases/3.1/#jsonfield-for-all-supported-database-backends
As stated in other answers, Django's native JSONField (as of 1.9 and 1.10) is for PostgreSQL.
Luckily, MySQL 5.7.8+ comes with a native JSON datatype. You can add it your Django project with the django-mysql package and Django 1.8+
pip install django-mysql
from django.db import models
from django_mysql.models import JSONField
class MyModel(models.Model):
my_json_field = JSONField()
Read more about the django_mysql JSONField here.
Django JSONField is Postgres only.
https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#django.contrib.postgres.fields.JSONField
UPDATE:
There is support for MYSQL via 3rd party library django-mysql
# Install jsonfield package
pip install jsonfield
# Define my model
from django.db import models
import jsonfield
class MyModel(models.Model):
the_json = jsonfield.JSONField()
More detail:https://pypi.python.org/pypi/django-jsonfield
I know this question is about Django 1.9, but JSONField can now be used with all supported database backends with the release of Django 3.1.
Try to save data of this model in postgres db on my local machine:
models.py:
from django.db import models
from django import forms
from inputData.models import Input
from django.contrib.postgres.fields import JSONField
class Results(models.Model):
generator = models.OneToOneField(Input, on_delete = models.CASCADE, primary_key = True)
pvalues = JSONField()
views.py
def result(req, res_id):
try:
inp = Input.objects.get(pk = res_id)
path = os.path.join(BASE_DIR, 'uploads\\' + str(res_id) + '\\t.txt')
p_values = parse_res.main(path)
res = Results(generator = inp, pvalues = p_values)
res.save(using = 'results')
except Results.DoesNotExist:
raise Http404
return render(req, 'result.html', {'res': res})
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'results': {
'ENGINE':'django.db.backends.postgresql',
'NAME': 'results',
'PASSWORD': 'password',
'USER': 'user',
'HOST': '127.0.0.1',
'PORT': '8000'
}
}
Model Results (see models.py) uses JSONField, which have about 200 bytes of data
But at the line res.save(... of code views.py browser does response too long.
Whatäs wrong with JSON?
What problems can be on server besides cache?
For today I'd recommend using jsonfield2 or waiting for native JSON support for all database backends in Django 3.