I am learning Django3.2.5, from https://docs.djangoproject.com/en/3.2/intro/tutorial02/. I created a project with the name, 'mysite', then 'polls' app, and using the default 'SQLite' database.
Project's (mysite) file hierarchy:
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
App's (polls) file hierarchy:
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
mysite/mysite/settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.29.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '4)2m9i5*y=icl-9bpiw#w#n!(y^y%38+8smh70mqupeppb&o#r'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'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 = '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/1.11/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.11/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.11/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.11/howto/static-files/
STATIC_URL = '/static/'
mysite/polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
mysite/polls/apps.py
from django.apps import AppConfig
class PollsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'polls'
When I run, python3 manage.py makemigrations polls, it throws out this error No installed app with label 'polls'.
I am new to Django, please help.
In Installed apps
you have written this
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
'polls.apps.PollsConfig', it is wrong syntax
instead of this write
INSTALLED_APPS = [
...
'polls.apps.PollsAppConfig',
...
]
Try python manage.py makemigrations
Without using 'polls'
Related
I run the following signals.py on (Ubuntu2204/WSL2 Windows 11) using Django 4.1.1 / Python 3.10
from .models import Sale
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
#receiver(m2m_changed, sender=Sale.positions.through)
def calculate_total_price(sender, instance, action, **kwargs):
print('action', action)
total_price = 0
if action == 'post_add' or action == 'post_remove':
for item in instance.get_positions():
total_price += item.price
instance.total_price = total_price
instance.save()
apps.py already signals in VSCode that signals is not used, this is also confirmed in the Django Debug Toolbar
from django.apps import AppConfig
class SalesConfig(AppConfig):
#default_auto_field = 'django.db.models.BigAutoField'
name = 'sales'
def ready(self):
import sales.signals
and then the __init__.py file
default_app_config = 'sales.apps.SalesConfig'
settings.py looks like this:
"""
Django settings for reports_proj project.
Generated by 'django-admin startproject' using Django 4.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
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/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-dbl^hk-m6-dz01+1i*hi5#rz4t90(y5s-cls1&0js5hj^ojo70"
# 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",
"debug_toolbar",
# my apps
"customers",
"products",
"profiles",
"reports",
"sales.apps.SalesConfig",
# 3rd party
"crispy_forms",
]
CRISPY_TEMPLATE_PACK = "bootstrap4"
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"debug_toolbar.middleware.DebugToolbarMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "reports_proj.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [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 = "reports_proj.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.1/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / 'static',
BASE_DIR / 'sales' / 'static',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
INTERNAL_IPS = [
"127.0.0.1",
]
Any hint would be highly appreciated, the code looks ok to me it must be some dependency issue but I have no idea where to start looking really
I just noticed that your ready identation is not correct, causing the problem...
You should change this:
from django.apps import AppConfig
class SalesConfig(AppConfig):
#default_auto_field = 'django.db.models.BigAutoField'
name = 'sales'
def ready(self):
import sales.signals
To this:
from django.apps import AppConfig
class SalesConfig(AppConfig):
#default_auto_field = 'django.db.models.BigAutoField'
name = 'sales'
def ready(self):
from . import signals
Generally because no indentation the method became global function and it was not called as it should.
I want to change DIRS dynamically.based on devices.
if request.user_agent.is_pc:
request.template_prefix = 'desktop'
else:
request.template_prefix = 'mobile'
Default (settings.py):
TEMPLATES = [
{
'DIRS': ['templates'],
},
]
I want to change my DIRS path like this (settings.py):
TEMPLATES = [
{
'DIRS': [f"templates/{request.template_prefix}"],
},
]
Also let me know if you need more codes.
Note: I can't use user_agent in settings.py Because it requires a request.
that's why I asked.
My django version is: 3.2.x
In simple words: How to change DIRS path in views.py.
Thanks!
Im new to Bazel.
I thought id start by trying to build a simple nodejs project, it uses babel to do some transforming as part of the build process, the issue im having is I cant seem to find a way to get these transformed files into a filegroup.
Here's my BUILD file.
load("#build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary")
load("#bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar")
# Group all our initial code.
filegroup(
name = "src",
srcs = [
".babelrc",
"package.json",
"//config:src",
"//handlers:src",
"//migrations:src",
"//models:src",
"//services:src",
"//tasks:src",
"#dependencies//:node_modules",
],
)
# Group all our generated code.
filegroup(
name = "out",
srcs = [
"//:babel:runfiles" ### ???
],
)
nodejs_binary(
name = "babel",
entry_point = "babel-cli/bin/babel.js",
templated_args = [
".",
"--ignore node_modules,test/,migrations/,babel_bin_loader.js",
"-d out",
"--source-maps=both",
"--copy-files",
],
node_modules = "#nodejs_build_tools//:node_modules",
data = [
"//:src",
]
)
pkg_tar(
name = "build",
strip_prefix = "/",
package_dir = "/usr/src/app",
srcs = ["//:out"],
mode = "0755",
)
My issue is that im not sure how to reference the runfiles from my nodejs_binary rule.
https://github.com/bazelbuild/rules_nodejs/blob/master/internal/node/node.bzl#L130
Seems to indicate that there should be a :runfiles attribute or similar?
Thanks! :)
So turns out that the correct way to do this appears to be by using a genrule to actually call the configured nodejs binary. Eg.
## Artifact Construction ##
genrule(
name = "construct_artifact",
outs = ["artifact.tar"],
cmd = """./$(location babel) . --ignore bazel-
out,node_modules,text/,migrations/ -d out/ --source-maps=both --copy-files && tar cvf $# out/ """,
srcs = [
"//:src",
],
tools = [
"//:babel",
]
)
I'm implementing haystack with the whoosh search engine. When I run 'rebuild_index' I get the following error in my terminal.
File "/home/dilts/installingDJANGO/ENV/lib/python3.5/site-packages/django/template/loader.py", line 74, in select_template
raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: search/indexes/submit_app/incident_text.txt
And this error in my browser.
reduce() of empty sequence with no initial value
incidents = SearchQuerySet().autocomplete(content_auto=request.POST.get(title, ''))
return clone.filter(six.moves.reduce(operator.__and__, query_bits))
My generic file structure looks like the following...
project
|--------submit_app
|--------search_app (uses a submit_app model called Incident)
|--------templates (where I put search/indexes/search_app/incident_text.txt)
From what I've read online, I believed my structure was correct, but from the error, I'm not so sure anymore. I feel like there might be some confusion with the shared model, but I don't know.
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
WHOOSH_INDEX = os.path.join(BASE_DIR,'whoosh/')
HAYSTACK_CONNECTIONS = {
'default':{
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': WHOOSH_INDEX,
},
}
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',
],
},
},
]
views.py
from django.shortcuts import render
from .forms import IncidentsSearchForm
from django.contrib.auth.decorators import login_required
from haystack.query import SearchQuerySet
#login_required(login_url='/login/')
def incidents(request):
if request.method == 'POST': # If the form has been submitted...
form = IncidentsSearchForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
title = form.cleaned_data['title']
## this piece isn't working at I had hoped
incidents = SearchQuerySet().autocomplete(content_auto=request.POST.get(title, ''))
else:
form = IncidentsSearchForm() # An unbound form
title = ''
incidents = ''
return render(request, 'search.html',
{
'form': form,
'title': title,
'incidents' : incidents,
}
)
when you include('haystack.urls'), it will look search/search.html by default. Are you have a search.html file ?
/templates/search/search.html
views.py
return render(request, 'search/search.html',
{
'form': form,
'title': title,
'incidents' : incidents,
}
I had the same issue with rebuild_index. It seems that Haystack looks for the txt template inside the model's app folder. In your case you should put the index in
templates/search/indexes/submit_app/incident_text.txt
submit_app not search_app
I'm migrating an out of date npm package from WAF to GYP, but having a few problems getting everything working. It runs a WSCRIPT which seems to include a 3rd party library:
import Options
from os import unlink, symlink, popen, sys
from os.path import exists
srcdir = '.'
blddir = 'build'
VERSION = '0.0.2'
def set_options(opt):
opt.tool_options('compiler_cxx')
def configure(conf):
conf.check_tool('compiler_cxx')
conf.check_tool('node_addon')
print(sys.platform)
if sys.platform == 'darwin':
conf.check_tool('osx')
tc_framework = 'TelldusCore'
conf.env.append_value("FRAMEWORK_TC", tc_framework)
tc_frameworkpath = '/Library/Frameworks/TelldusCore.framework/'
conf.env.append_value("FRAMEWORKPATH_TC", tc_frameworkpath)
tc_lib = tc_frameworkpath + 'Headers/'
conf.env.append_value("CPPPATH_TC", tc_lib)
elif sys.platform == 'linux2':
conf.env.LIB_TC = 'telldus-core'
#conf.env.LIBPATH_TC = ['/usr/lib']
#conf.env.CCFLAGS_TC = ['-O0']
conf.env.CCDEFINES_TC = ['TC']
#conf.env.LINKFLAGS_TC = ['-g']
else:
raise ValueError("Dose not support: %r" % sys.platform)
def build(bld):
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
obj.target = 'telldus'
obj.source = 'telldus.cc'
obj.uselib = "TC"
Now I've tried to convert it to a binding.gyp script, but not sure how to include the library:
{
"targets": [
{
"target_name": "tellduscorejs2",
"sources": [ "tellduscorejs2.cpp" ],
"conditions": [
['OS=="mac"', {
'defines': [
'FRAMEWORK_TC=TelldusCore',
'FRAMEWORKPATH_TC="/Library/Frameworks/TelldusCore.framework/"',
'CPPPATH_TC="/Library/Frameworks/TelldusCore.framework/Headers/"'
]
}],
['OS=="linux"', {
'defines': [
'LIB_TC=telldus-core',
'CCDEFINES_TC=TC'
]
}]
],
'link_settings': {
'libraries': [
???
],
},
}
]
}
If anyone could point out if I'm on the right lines or what I need to change to include the library it'd be appreciated!
I've actually done this for the telldus-core project. See https://github.com/marchaos/telldus-core-js/
i've also added events for devices and sensors.