I am trying to import a module in my views.py as
from django.shortcuts import render
# Create your views here.
from viewcreator import Builder
import json
def index(request):
a,b=Builder.buildChartJSON()
print(json.dumps(a))
print(json.dumps(b))
return render(request, 'hdfsStats/hdfscharts.html',
{'sourcepoints': a, 'sizepoints': b})
and here is how my project setup looks like
why cant i import the modules in my view? I do not want to create these classes in the models.py. These classes are just meant to run some calculations and return two json objects, which i then feed to my webpage
here is my settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.9.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/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/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '9mxuqginh(vhh*2eu6j58kbq+%+7ql4_pn3k#yf+n96uv0rymq'
# 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',
'hdfsStats.apps.HdfsstatsConfig'
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/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/1.9/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/1.9/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/1.9/howto/static-files/
STATIC_URL = '/static/'
am i missing any configuration?
Stacktrace
File "XXX:\mysite\hdfsStats\urls.py", l
ine 3, in <module>
from . import views
File "XXX:\mysite\hdfsStats\views.py",
line 5, in <module>
from viewcreator import Builder
ImportError: No module named 'viewcreator'
Update
current structure
and my views.py
from django.shortcuts import render
# Create your views here.
from .src.viewcreator import Builder
import json
def index(request):
a,b=Builder.buildChartJSON()
print(json.dumps(a))
print(json.dumps(b))
return render(request, 'hdfsStats/hdfscharts.html',
{'sourcepoints': a, 'sizepoints': b})
but now i get
from propreader import ReadProp
ImportError: No module named 'propreader'
basically, i have four packages
viewcreator
propreader
esconnector
ping
the classes in these packages perform some calculations based on the properties files in the these two folders
props
resources
which i have put at the same level as src folder
Since these are one time calculations, i dont want to create models for these. What is the proper way for me to configure my Django project in this scenario? I need the Django project to host a webpage that will display the results of my calculations.
In your INSTALLED_APPS
INSTALLED_APPS = [
...,
'HdfsstatsConfig',
]
in your views.py
from .viewcreator import Builder
UPDATE, DJANGO IMPORTS
There are 3 ways to imports module in django
1. Absolute import:
Import a module from outside your current application
Example
from myapp.views import HomeView
2. Explicit import:
Import a module from inside you current application
3. Relative import:
Same as explicit import but not recommended
from models import MyModel
Related
I'd like to display the contents of a JSON file through a GET request.
In views.py I use a GET request to open data2.json. The file is in the same directory as views.py.
But I get the following error:
File "C:\Users\Kaik\Documents\djangoPractice\shopping_cart\api_app\views.py", line 134, in get
with open(pdfPath2,"r") as file:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Kaik\\Documents\\djangoPractice\\shopping_cart\\api_app'
[12/Jun/2022 11:14:04] "GET /study/data2.json HTTP/1.1" 500 90058
Here is the GET in views:
from django.views import View
from django.http import JsonResponse
import json
from shopping_cart import settings
from .models import CartItem
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from . import studyduck_all
from . import iniStudyduck
from iniStudyduck import initiateDuck
import os
def get(self, request, pdfname):
path = os.getcwd()
pdfPath = os.path.join(path, 'api_app')
pdfPath2 = os.path.join(settings.MEDIA_ROOT, 'textfile.txt')
jsonData = ''
with open(pdfPath2,"r") as file:
jsonData = json.load(file)
return JsonResponse(jsonData)
Here is my SETTINGS:
"""
Django settings for shopping_cart project.
Generated by 'django-admin startproject' using Django 2.2.5.
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 # new
from pathlib import Path
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print("HERE IS THE BASE DIR ", BASE_DIR)
# 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 = 'HIDDEN'
# 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',
'api_app',
]
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 = 'shopping_cart.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 = 'shopping_cart.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',
},
]
STATICFILES_DIRS = [
BASE_DIR + "/static",
BASE_DIR + '/api_app/PDFs',
]
print("STATICFILES_DIRS" , STATICFILES_DIRS)
# 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/'
# Path where media is stored # TEMP
MEDIA_ROOT = os.path.join(BASE_DIR, 'api_app/PDFs')
and here is urls.py
from django.urls import path
from .views import ShoppingCart, ShoppingCartUpdate, StudyDuck
urlpatterns = [
path('cart-items/', ShoppingCart.as_view()),
path('update-item/<int:item_id>', ShoppingCartUpdate.as_view()),
path('study/<str:pdfname>', StudyDuck.as_view()),
]
I've tried a number of things including changing location of data2.json to be reflected in settings static files, tried to change permissions (I'm on a windows but not sure how to do this on Windows)....
Any help would be appreciated.
Just started a fresh Django Rest framework project and I'm getting stuck on importing a view (TodoView) in urls.py
This is a completely fresh project, all I did was add the model, view and now attempting to add the url.
File "C:\Users\Simon\Documents\GitHub\tradingjournal\django_backend\django_backend\urls.py", line 20, in <module>
from django_backend.todo.views import TodoView
ModuleNotFoundError: No module named 'django_backend.todo'
urls.py
from django.contrib import admin
from django.urls import path
from rest_framework import routers
from django_backend.todo.views import TodoView
router = routers.DefaultRouter()
router.register(r'todos', TodoView, 'todo')
urlpatterns = [
path('admin/', admin.site.urls),
]
views.py
from django.shortcuts import render
# Create your views here.
from rest_framework import viewsets
from django_backend.todo.models import Todo
from django_backend.todo.serializers import TodoSerializer
class TodoView(viewsets.ModelViewSet):
serializer_class = TodoSerializer
queryset = Todo.objects.all()
settings.py
"""
Django settings for django_backend project.
Generated by 'django-admin startproject' using Django 3.0.7.
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__)))
# 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 = 'n3^zfbj#c&i-9v^8q(%iox!kuy#gy2liy-1b+)q21-g&nwezf('
# 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',
'rest_framework',
'corsheaders',
'todo',
]
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',
'corsheaders.middleware.CorsMiddleware',
]
ROOT_URLCONF = 'django_backend.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 = 'django_backend.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/'
I tried changing django_backend.todo.views to todo.views but as you can see in the screenshot it's not recognized:
In a Django project the directory name of the project really doesn't matter in the code so instead of
from django_backend.todo.views import TodoView
you need to be writing:
from todo.views import TodoView
Next you see pycharm complaining that this is not a valid import while in fact it actually is (can be seen by actually running the project). Why does this happen? It is because it considers your projects root directory (i.e. there is likely a directory above django_backend) as the sources root and hence is unable to resolve your imports. To solve this you just need to set it as the Sources root by following these steps:
Right click on the project directory i.e. django_backend (on the project structure on the left side)
Select the option "Mark Directory As"
Click "Sources root"
when I deploy *my heroku website everything loads up except my The Website Images you could see everything but it shows the images as errors I am not sure how to fix this I been stuck with this problem for almost 2 days if you know how to fix it please explain it to me so in the future I could go back and see this and fix my problem I literally have all the requirements for my website to be launched with heroku but I am not see the images at all
my settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 3.1.1.
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/
"""
import os
from pathlib import Path
# 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 = False # remember to change to false
ALLOWED_HOSTS = ['anim3-domain.herokuapp.com']
# 'https://anime-domain.herokuapp.com/'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main.apps.MainConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'mysite.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 = 'mysite.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 = '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_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
my urls
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("main.url")),
]
my wsgi.py
"""
WSGI config for mysite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_wsgi_application()
here is part of the error log
rWarning: No directory at: /app/staticfiles/
2020-10-10T16:21:57.649046+00:00 app[web.1]: warnings.warn(u"No directory at: {}".format(root))
2020-10-10T16:21:57.649987+00:00 app[web.1]: /app/.heroku/python/lib/python3.6/site-packages/whitenoise/base.py:115: UserWarning: No directory at: /app/staticfiles/
2020-10-10T16:21:57.649989+00:00 app[web.1]: warnings.warn(u"No directory at: {}".format(root))
heres the full error log its in pastebin because its to long stack will view it as error
https://pastebin.com/fEr8LQk1
This question resulted from a suggestion to my original issue of getting Local day from a database that is storing things as UTC located HERE
I had an issue with getting some UTC as local time values from a database in my django app as I was doing it be 'hand' in my script, someone in that issue (located here) suggested I try running the script with django (reworking to use the django ORM) decent idea but then get this error which is coming from my models file here:
from __future__ import unicode_literals
from django.db import models
from django.db.models import Q
from django.contrib.auth.models import User
# Create your models here.
class OnSiteLog(models.Model):
objects = models.Manager()
user = models.ForeignKey(User, on_delete=models.CASCADE)
...
So the full error I get is:
Traceback (most recent call last):
File "report_mailer_django.py", line 13, in <module>
from covidlog.models import OnSiteLog
File "/mnt/h/programming/web/covid19/covidlog/models.py", line 7, in <module>
from django.contrib.auth.models import User
File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/models.py", line 3, in <module>
from django.contrib.contenttypes.models import ContentType
File "/usr/local/lib/python3.6/dist-packages/django/contrib/contenttypes/models.py", line 133, in <module>
class ContentType(models.Model):
File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 111, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
I am not sure what is causing this, the file I am trying to fun should be loading django stuff just fine:
import django
import os
from django.conf import settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "covid19.settings")
settings.configure()
django.setup()
# Now this script or any imported module can use any part of Django it needs.
from covidlog.models import OnSiteLog
from covidlog.models import CountTracker
def getCheckins():
...
...
Maybe I am missing something in my settings file?
My directory structure of my project is:
covid19/
covid19/
__init__.py
settings.py
etc...
covidlog/
__init__.py
apps.py
forms.py
models.py
views.py
etc...
manage.py
report_mailer_django.py <<- what I am trying to get to run....
Also my settings file:
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 = 'l*s*!daf#_q&mbdp-$wq&5wq-6964c2z4s49!e9c+-az42br8f'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
# Application definition
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
'covidlog.apps.CovidlogConfig',
'django.contrib.admin',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'bootstrap4',
'covid19',
]
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 = 'covid19.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'covidlog/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 = 'covid19.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 = 'MST'
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/'
I splited my settings.py like this:
# __init__.py
from .base import * # noqa
try:
from .local_settings import * # noqa
except ImportError:
message = 'ERROR: Unable to import local_settings. Make sure it exists.'
raise ImportError(message)
# base.py
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 3.0.4.
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.dirname(os.path.abspath(__file__))))
# Add the apps folder to python path
os.sys.path.append(os.path.join(BASE_DIR, 'apps'))
# Application definition
INSTALLED_APPS = [
'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 = 'app.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 = 'app.wsgi.application'
# 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',
},
]
and:
# local_settings.py
import os
from .base import BASE_DIR
# 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 = '670b9a538dfe8545f4eff723345da43211084a05f520a2d638'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'run/db.sqlite3'),
}
}
# 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/'
Every command works good except python manage.py startapp myapp [or any other app name] ./apps/myapp. Every time I run it command I get this error:
CommandError: 'myapp' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name.
I found it related with my code in __init__.py file. I mean if I comment all the codes, that error will be disappear.
Why does it happend? How can I solve it?
With Directory
Without Directory
As #juggernaut has stated. The error is happening when you use the character *, which imports everything and hence overwrites some internal.
When you run the command python manage.py startapp myapp xxxx The myapp section conflicts with an existing module and hence causes that error.
Try importing it manually instead of using from .base import * # noqa. This way you only import the modules that you will need and would not lead to any errors.