How to change `DIRS` path dynamically in Django? - python-3.x

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!

Related

Create ESLint rule for TS files only

I'm writing a custom plugin that based on various conditions, it fixes an error by passing a new type. for example,
before the fix:
const x = X("A");
~ <-- Error
after the fix:
const x = X<A>("A");
Everything seems to working, except the part where the following rule is being enforced in JS files as well. How can I enforce the rule to run only in TS files?
One way to achive this, is to use "overrides" in your .eslintrc.js file. to only enable it on .ts files and keep the rest of your eslint config the same:
You can look at this in more detail on https://eslint.org/docs/latest/user-guide/configuring/configuration-files#configuration-based-on-glob-patterns
Example:
module.exports = {
...
"overrides": [
"files": [
"**/*.ts"
],
"rules": {
"your-cool-rule": "error"
}
]
...
}

How can I install extension of vscode?

This is a beginner question. So there is a package vscode-with-extensions.
The package says:
A set of vscode extensions to be installed alongside the editor. Here's a an example:
vscode-with-extensions.override {
# When the extension is already available in the default extensions set.
vscodeExtensions = with vscode-extensions; [
bbenoist.Nix
]
# Concise version from the vscode market place when not available in the default set.
++ vscode-utils.extensionsFromVscodeMarketplace [
{
name = "code-runner";
publisher = "formulahendry";
version = "0.6.33";
sha256 = "166ia73vrcl5c9hm4q1a73qdn56m0jc7flfsk5p5q41na9f10lb0";
}
];
}
Where in configuration.nix do I have to put this expression? I already have
environment.systemPackages = with pkgs; [
wget
vim
vscode-with-extensions
];
therein.
You’re supposed to use it as in the configuration.nix directly, like for instance
environment.systemPackages = with pkgs; [
wget
vim
(vscode-with-extensions.override {
# When the extension is already available in the default extensions set.
vscodeExtensions = with vscode-extensions; [
bbenoist.Nix
]
# Concise version from the vscode market place when not available in the default set.
++ vscode-utils.extensionsFromVscodeMarketplace [
{
name = "code-runner";
publisher = "formulahendry";
version = "0.6.33";
sha256 = "166ia73vrcl5c9hm4q1a73qdn56m0jc7flfsk5p5q41na9f10lb0";
}
];
})
];
Or, in a more readable version:
environment.systemPackages = with pkgs;
let
vcsodeWithExtension = vscode-with-extensions.override {
# When the extension is already available in the default extensions set.
vscodeExtensions = with vscode-extensions; [
bbenoist.Nix
]
# Concise version from the vscode market place when not available in the default set.
++ vscode-utils.extensionsFromVscodeMarketplace [
{
name = "code-runner";
publisher = "formulahendry";
version = "0.6.33";
sha256 = "166ia73vrcl5c9hm4q1a73qdn56m0jc7flfsk5p5q41na9f10lb0";
}
];
})
in
[
wget
vim
vcsodeWithExtension
];
So, apparently it can go directly into environment.systemPackages, but requires parentheses:
environment.systemPackages = with pkgs; [
wget
vim
(vscode-with-extensions.override {
vscodeExtensions = with vscode-extensions; [
bbenoist.Nix
];
})
];

Including runfiles in a filegroup

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",
]
)

(haystack + woosh) 'rebuild_index' looking for template in wrong location?

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

Migrating from WAF to GYP - trouble including library

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.

Resources