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

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

Related

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.

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

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

In Django multiple databases should not creat a test database by manage.py on 1 specific database

In Django I'm using multple databases, but by testing the functionality 1 database of the multiple database should not create a test database if you run manage.py test **. How can I solve this issue.
In your settings.py you can tell Django what database to use when testing. Here is the code to do so if you would like to use SQLite for example:
settings.py:
if 'test' in sys.argv:
DATABASES['default'] = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'tests.db',
}
Django creates a new database every time you run your manage.py test, so you would want to use fixtures in your test.py file to preload you database with data before running tests (if you need it preloaded with data).
To generate a fixture for the User model for example, use this code:
python manage.py dumpdata auth.User --indent=2 > app_name/fixtures/admin.json
To use fixtures you would structure your tests.py like so:
tests.py:
from django.test import TestCase
class MyTests(TestCase):
fixtures = [admin.json]
def setUp(self):
# other setup code here
def test_the_obvious(self):
assert True == True

Scrapy pipeline django sqlite3 database error on save

It seems that Scrapy can't see database because item.save() return error. django.db.utils.DatabaseError: no such table: myapp_myitem It's not problem with Django model because I can add/edit it from Django admin without errors.
items.py
from scrapy.contrib.djangoitem import DjangoItem
from myapp.models import Myitem
class MyitemItem(DjangoItem):
django_model = Myitem
pipelines.py
from myapp.models import Myitem
from items.models import License, Category, Special
class MyitemPipeline(object):
def process_item(self, item, spider):
item.save()
return item
settings.py
ITEM_PIPELINES = {
'scrapyproject.pipelines.MyitemPipeline':1000,
}
import sys
sys.path.append('path_to_project')
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings.local'
my_django_project/settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db/local_db',
'USER': 'me',
}
I'll answer to my question after I fix the problem because it's trivial problem which take from me all day. Maybe it can be useful to someone.
After I change NAME of database to absolute path to the sqlite3 database Scrapy was store data successfuly. So Scrapy need absolue path to the sqlite3 database and changing name to absolute path to the db will not affect Django functionality.