Django mange.py migrate --> No Migration folder and no tables created - python

I recently started to experiment with python and Django at the same time. After playing with several little projects from GitHub and or youtube and tried do it from scratch now on my own.
My problem is, the command
python manage.py migrate
Only creates those 10 "standard" Django and "auth" tables in my local mysql db.
Attached you can find my project structure. The way I started was with " django-admin startproject Nico".
Then step after step've created models, views, forms and templates.
My best guess is, the migrate command does not find the models file.
But I don't know where to specify that. At least that is a missing link. In my previous examples which were complete, I never had to declare that. Would that go in the right direction?
views.py
from django.views.generic.base import TemplateView
from ReProg.ReProg.models import Kunde
from ReProg.ReProg.forms import KundeForm
class HP(TemplateView):
Model = Kunde
Form = KundeForm
#template_name = "TestViewHello.html"
#template_name = "KundenAufnahme.html"
template_name = "KundenAufnahme2.html"
forms.py
from django import forms
from django.http import HttpResponse, HttpResponseNotFound
from django.shortcuts import render
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class KundeForm(forms.Form):
#KID = forms.CharField(attrs={'disabled': True})
KID = forms.CharField()
first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'ReProg'}))
last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Wilhelm'}))
email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': '123#Mail.com'}))
def __init__(self, *args, **kwargs):
super(KundeForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', 'Submit'))
Models.py
from django.db import models
from django.forms import ModelForm
from datetime import date
###########Kunde
class Kunde(models.Model):
KID = models.CharField(primary_key=True, max_length=20)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=100, blank=True)
def KID(key):
num = Request.objects.all().count()
return K + str(num)
class KundeMF(ModelForm):
class Meta:
model = Kunde
fields = ['first_name', 'last_name', 'KID']
settings.py
Django settings for ReProg project.
Generated by 'django-admin startproject' using Django 3.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+e69jgm56u85imt)(=6#82#c60222e9-z0+h8b+kxwhe(kc*z4'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ReProg',
'crispy_forms',
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ReProg.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ReProg.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'ReProg',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'

python manage.py makemigrations <app name>
python manage.py migrate <app name>

first make the following
python manage.py makemigrations
python manage.py migrate
if the problem did not solved make the following:
1- If the folder migrations did not found in the app directory create it.
2- If the folder found check the __init__.py file inside the folder.
if this file did not found create new file with name __init__.py.

it worked with adding the
i forgot to mention that before migrating I executed "makemigrations".
However it said "no changes detected" or something similar.
Now with the it works. I can see the table now in mysql.
[enter image description here][1]
thx all
[1]: https://i.stack.imgur.com/HaKFg.png

Related

Django to Heroku, How to migrate sqlite3 data to postgres

I tried to host a website on heroku but I keep getting this error
File
"/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "home_product" does not
exist LINE 1: ...home_product"."price", "home_product"."slug" FROM
"home_prod...
whenever I tried to use
heroku run python
manage.py migrate -a appname
I mainly used this video as a reference to hosting.
and also this StackOverflow question and this article didn't shed much light on the issue.
Here's my settings.py
"""
Django settings for Corbett_Jewelry project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
import django_heroku
import dj_database_url
from decouple import config
import psycopg2
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'
ALLOWED_HOSTS = ['127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'Corbett_Jewelry.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'Corbett_Jewelry.wsgi.application'
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
django_heroku.settings(locals())
My models.py:
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
image = models.ImageField(blank=True)
desc = models.TextField()
price = models.IntegerField()
slug = models.SlugField(unique=True, default=None)
def __str__(self):
return self.name
class Images(models.Model):
product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE)
img = models.ImageField(upload_to='images/')
def __str__(self):
return self.product.name
class Beads(models.Model):
name = models.CharField(max_length=200)
price = models.IntegerField()
img = models.ImageField(upload_to='beads/')
My Procfile:
web: gunicorn Corbett_Jewelry.wsgi
My requirements.txt:
asgiref==3.4.1
cycler==0.10.0
dj-database-url==0.5.0
Django==3.2.9
django-heroku==0.3.1
gunicorn==20.1.0
kiwisolver==1.3.2
matplotlib==3.4.3
numpy==1.21.2
Pillow==8.3.2
psycopg2==2.9.2
pyparsing==2.4.7
python-dateutil==2.8.2
python-decouple==3.5
pytz==2021.3
selenium==3.141.0
six==1.16.0
sqlparse==0.4.2
urllib3==1.26.7
whitenoise==5.3.0
I don't know what else information you might need to solve this. I'm happy to provide any info since I've been banging my head over this for a week now.
#Gamingapple... as you asked in the comments, I will attempt to provide all possible solutions I can think of for your issue.
I have never use Heroku, but here are the first solutions I would try:
1. A quick read from Heroku's help docs is showing you perhaps are not running migrations in the way that Heroku thinks are best practices for migrations: https://help.heroku.com/GDQ74SU2/django-migrations there (more-or-less) means you should be running your migrations locally, pushing up to Git, and then Heroku will automate the running of your migrations on deploy where it states:
Then, add the following as the first line in your Procfile:
release: python manage.py migrate
But note that this also means you should be using Postgres locally in development, not SQLite (as your title suggests).
-- Along with this, it appears you are trying to run migrations by app when you do: manage.py migrate -a appname, Django does have some regular migrations that need to be run so I'd just try manage.py migrate
2. You noted in the comment that dj_database_url.config() from PyPi's dj_database_url package: https://pypi.org/project/dj-database-url/ is returning an empty dictionary. To me, without extra info, I would say this is where your problem is when you manually try to run migrate in your Heroku instance; there is no database to find or connect to. To fix this I would remove the use of dj_database_url (as I have not used it either and we are debugging), and manually write my connection string for Django's DATABASES, like so:
pip install psycopg2 or just ensure it is in requirements/installed.
Change your DATABASES attr in settings to be manually written so you know what it is (we are debugging so perhaps after you get it up you make the password gathering more secure, like as an env variable)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '[HEROKU DB NAME]',
'USER': '[HEROKU DB USERNAME]',
'PASSWORD': '[HEROKU PASSWORD]',
'HOST': '{HEROKU HOST IP OR NAME FOR YOUR DB]',
'PORT': '[HEROKU DB PORT]',
}
}
Now with that correct, run the migration commands:
python manage.py makemigrations
python manage.py migrate

Python Django - Internal Error ProgrammingError relation does not exist

This might probably be a duplicated question, but I can't find a post to answer my questions yet. Any post that is similar to this may help is appreciated.
I tried to host my Django app using heroku.com
git add .
git commit -m "(commit_name)"
git push heroku master
When I tried to test the website (/questions/1), the website shows an Error 500 (Internal Error).
First it shows a ProgrammingError: relation does not exist.
After that I did $ heroku run python manage.py migrate try to solve the problem. The original error disappeared, but instead this happened:
2020-08-29T11:05:42.668070+00:00 app[web.1]: Internal Server Error: /questions/1
2020-08-29T11:05:42.668070+00:00 app[web.1]:
2020-08-29T11:05:42.668070+00:00 app[web.1]: DoesNotExist at /questions/1
2020-08-29T11:05:42.668071+00:00 app[web.1]: Question matching query does not exist.
Settings.py:
import django_heroku
from pathlib import Path
import os
#--------------------(ommited)--------------------#
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myweb.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'myweb.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'zh-Hant'
TIME_ZONE = 'Asia/Taipei'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Activate Django-Heroku.
django_heroku.settings(locals())
Models.py:
from django.db import models
from django.utils import timezone
import json
# Create your models here.
class Code(models.Model):
code = models.TextField()
number = models.IntegerField()
class Question(models.Model):
title = models.TextField()
text = models.TextField()
judges = models.TextField()
number = models.IntegerField()
class Meta:
ordering = ['number']
def set_judges(self, x):
self.judges = json.dumps(x)
def get_judges(self):
return json.loads(self.judges)
wsgi.py:
import os
from dj_static import Cling
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myweb.settings')
application = Cling(get_wsgi_application())
Any suggestions or things I should try? Thank you.
[EDIT]: It seems that the database is empty now so it cause the error. But when I run the same file in my computer as I git push to heroku, the database isn't empty and it works fine.
According to your settings file, you are using sqlite as the database, and you can't use it in Heroku.
Heroku uses an an ephemeral filesystem.
You can write to it, and you can read from it, but the contents will
be cleared periodically. If you were to use SQLite on Heroku, you
would lose your entire database at least once every 24 hours.
That's why it works locally but not on Heroku, you need to use another database engine like postgresql for example.
Learn more about it at: https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted

ImportError: attempted relative import with no known parent package when running main.py

I am using Django 3.0 for my project and want to make a simple registration page. My registration information is not showing up on the admin database page. python manage.py runserver is not raising any errors but admin.py and views.py have import errors. I'm also sharing same code snippet. Here are some snippet of my admin.py, views.py, models.py and settings.py.
error
[Running] python -u "g:\Study\Python\Django Project\checkproject\checkapp\views.py"
Traceback (most recent call last):
File "g:\Study\Python\Django Project\checkproject\checkapp\views.py", line 3, in <module>
from .models import registerPerson
ImportError: attempted relative import with no known parent package
admin.py
from django.contrib import admin
from .models import registerPerson
class register(admin.ModelAdmin):
list_display = ['firstname', 'lastname', 'email', 'password']
admin.site.register(registerPerson,register)
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import registerPerson
def register(request):
return render(request,'registration.html')
def add_registration(request):
firstname = request.POST["first_name"]
lastname = request.POST["lastname"]
email = request.POST["email"]
password = request.POST["password"]
info = registerPerson(firstname=firstname, lastname=lastname, email=email, password=password)
info.save()
return render(request,'registration.html')
models.py
from django.db import models
# Create your models here.
class registerPerson(models.Model):
firstname=models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
email = models.CharField(max_length=30)
password = models.CharField(max_length=32)
def __str__(self):
return self.firstname
settings.py
["""
Django settings for checkProject project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR=os.path.join(BASE_DIR,'checkapp/templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6rst-p=7+k*hq*21uynw_rj)=s2iqh668_hun-vg7+!##uni9o'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = \[\]
# Application definition
INSTALLED_APPS = \[
'checkapp.apps.CheckappConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
\]
MIDDLEWARE = \[
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
\]
ROOT_URLCONF = 'checkProject.urls'
TEMPLATES = \[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': \[TEMPLATES_DIR\],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': \[
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
\],
},
},
\]
WSGI_APPLICATION = 'checkProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = \[
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
\]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
here is my project tree structure
CHECKPROJECT
checkapp
_pycache
migrations
templates
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
checkProject
__pycache__
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
db.sqlite3
manage.py

Issue creating instance of Django model when model uses datetime?

I am currently making a project in Django that has two models: Cards and Articles. Both cards and articles have a manager that should allow me to quickly instantiate instances of the class. For cards I have the following:
class CardsManager(models.Manager):
def create_card(self, card_name, geography, player, typestatus, _weighted_strength = 0):
card = self.update_or_create(card_name=card_name, geography=geography, player=player, typestatus=typestatus)
return card
This manager works smoothly and I have no issue uploading cards. However, my article manager is a different story. This is my article manager.
class ArticleManager(models.Manager):
def create_article(self, title, body, cardvar, source, datetime, readthrough, author):
article_item = self.update_or_create(title=title, body=body, card=cardvar, source=source, entry_date_time=datetime, read_through=readthrough, cardvar__card_name=cardvar, author=author)
return article_item
When I try to upload an article however, say in the following fashion:
article_entry = Article.objects.create_article('title', 'empty body', 'test_card_var', 'The_Source', '2019-12-30 02:03:04', 0, 'author')
I get the following error in my Powrshell when I simply attempt 'python manage.py runserver': LookupError: No Installed app with label 'admin'.
When I attempt to run 'python manage.py makemigrations' I get another long error message whose last line is 'django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.'
I think the issue may have to do with something related to either 1) entry_date_time being a datetime object and passing a string (though I honestly am not sure how I'd pass a datetime object, what do they even look like) or b) the fact that cardvar is a ForeignKey pointing at the Cards model, which may not be allowed in an upload?
I really had no issues with uploading Cards but Articles has given serious issues. If anyone could help me resolve this issue it would be greatly appreciated, I'm still relatively new with Django and coding in general.
EDIT:
My Settings.py looks as follows:
"""
Django settings for newspaper_project project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
#import django_heroku
#import psycopg2
#import dj_database_url
#import dotenv
#import psycopg2
#import dj_database_url, psycopg2
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#DATABASE_URL = os.environ['DATABASE_URL']
#conn = psycopg2.connect(DATABASE_URL, sslmode='require')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ***********************
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#3rd party
'crispy_forms', #new
#Local
'users.apps.UsersConfig',
'pages.apps.PagesConfig',
'articles.apps.ArticlesConfig', #new
]
TIME_ZONE = 'America/New_York' #new
USE_TZ = True #TESTING THIS OUT
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'newspaper_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], #new
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'newspaper_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
AUTH_USER_MODEL = 'users.CustomUser' #new
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #new
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = '**************************************'
EMAIL_PORT = 587
EMAIL_USE_TILS = True

django docker db migrations is not working for the new model

I am new here in django docker.
I have created new model for django app, I am working on docker. When I am trying to use migrate command docker exec -ti 75ce87c91dc7 sh -c "python app/manage.py migrate", it says: No migrations to apply. Here I have added my models.py file, do we need to import this models to anywhere else?
Folder Structure :
settings.py
"""
Django settings for trialriskincApi project.
Generated by 'django-admin startproject' using Django 2.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xh86wu$_k#g46*+y9v_$2q^jnfg$uc44yh4+15nl2+2dx^$il%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['0.0.0.0']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'trialriskincApi',
]
MIDDLEWARE = [
'trialriskincApi.middleware.open_access_middleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'trialriskincApi.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'trialriskincApi.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'trail_risk_inc_backend',
'USER': 'root',
'PASSWORD': '12345678',
'HOST': 'db', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
# Cors headers
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]
models.py
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Userprofile(models.Model) :
user = models.OneToOneField(User, on_delete=models.CASCADE)
type = models.SmallIntegerField(max_length=1)
created_date = models.DateTimeField(default=timezone.now)
updated_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.updated_date = timezone.now()
self.save()
def __str__(self):
return self.title
If you are getting No changes detected that suggests that Django is not discovering your models.py, given that you are using the project as your app as well, I am guessing you forgot to add your project name (which is the same as your app name) in your INSTALLED_APPS.
e.g. in settings.py
INSTALLED_APPS = (
...
"trialriskincApi",
)
To migrate a new model you have to run
python manage.py makemigrations <yourAppName>
And for Docker you do like this:
docker exec -ti 75ce87c91dc7 sh -c "python app/manage.py makemigrations <yourAppName>

Categories

Resources