Display query-set results on a Django template without using a django model - python-3.x

AttributeError at /Blog/mycustomsql
module 'django.http.request' has no attribute 'META'
Request Method: GET
Request URL: http://127.0.0.1:8000/Blog/mycustomsql
Django Version: 2.1.5
Exception Type: AttributeError
Exception Value:
module 'django.http.request' has no attribute 'META'
Exception Location: C:\Users\c822208\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\context_processors.py in debug, line 40
Python Executable: C:\Users\c822208\AppData\Local\Programs\Python\Python37\python.exe
Python Version: 3.7.3
Python Path:
['C:\cygwin64\home\c822208\django\hr',
'C:\Users\c822208\AppData\Local\Programs\Python\Python37\python37.zip',
'C:\Users\c822208\AppData\Local\Programs\Python\Python37\DLLs',
'C:\Users\c822208\AppData\Local\Programs\Python\Python37\lib',
'C:\Users\c822208\AppData\Local\Programs\Python\Python37',
'C:\Users\c822208\AppData\Local\Programs\Python\Python37\lib\site-packages']
Server time: Wed, 9 Oct 2019 08:58:49 +0000
def mycustomsql(self):
import cx_Oracle
conn_string = cx_Oracle.connect('hr/passwd#127.0.0.1/xe')
cursor1=conn_string.cursor()
cursor2=conn_string.cursor()
cursor1.execute("SELECT p.name,p.value FROM v$parameter p ORDER BY p.name")
results1 = cursor1.fetchall()
cursor2.execute("SELECT p.name,p.value FROM v_param p ORDER BY p.name")
results2 = cursor2.fetchall()
for index in range(0,len(results1)):
if results2[index] == results1[index]:
# print ('Found')
continue
rs= (results1[index]," : ",results2[index])
# return HttpResponse(rs) -- this is giving me one row instead of 2
context = {
"object_list": rs
}
return render(request, "Blog/param.html", context)
python python_tut/query.py
localhost/xe - ('shared_pool_size', '0') : localhost/xe - ('shared_pool_size', '5')
localhost/xe - ('streams_pool_size', '0') : localhost/xe - ('streams_pool_size', '8')

Related

HTTPSConnectionPool(host='127.0.0.1', port=7545): Max retries exceeded with url: (Caused by NewConnectionError

# compile_standart is going to be the main function that we will use to compile this code.
from solcx import compile_standard, install_solc
import json
from web3 import Web3
import os
from dotenv import load_dotenv
load_dotenv()
with open("./SimpleStorage.sol", "r") as file:
simple_storage_file = file.read()
print("Installing...")
install_solc("0.6.0")
# print(simple_storage_file)
# compile our solidity
compiled_sol = compile_standard(
{
"language": "Solidity",
"sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
"settings": {
"outputSelection": {
"*": {
"*": [
"abi",
"metadata",
"evm.bytecode",
"evm.bytecode.sourceMap",
] # (ABI=Application Binary Interface)EVM (Ethereum Virtual Machine) is the core component of the Ethereum network
}
}
},
},
solc_version="0.6.0",
)
# print(compiled_sol)
with open("compiled_code.json", "w") as file: # w means it wil wright from it
json.dump(
compiled_sol, file
) # is it's going to take our compiled soul jason variable and just dump it into this (file) here
# but still it is going to keep it in json syntax
# get bytecode
bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"][
"bytecode"
]["object"]
# get abi
abi = json.loads(
compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["metadata"]
)["output"]["abi"]
# for connecting to ganache
w3 = Web3(Web3.HTTPProvider("https://127.0.0.1:7545"))
chain_id = 5777
my_address = "0x630Ee320BcE235224184A31FC687a5D183142BB9"
private_key = "0xd3cf1f678e8a78ace754cf57bd6ebcb28852e9657bb371951d72bbb5a0a3f413"
# private_key = os.getenv(" PRIVATE_KEY ")
# print(private_key)
# Create the contract in Python
SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)
# print(SimpleStorage)
# Get the latest transaction
**nonce = w3.eth.getTransactionCount(my_address)**(I'm having this error in this line)[![**enter image description here**][1]][1]
# print (nounce)
# we could see that the number of transaction=0 because we haven't made any
# 1. Build a transaction
# 2. Sign a transaction
# 3 . Send a transaction
transaction = SimpleStorage.constructor().buildTransaction(
{" chainId ": chain_id, " from ": my_address, " nonce ": nonce}
)
# print(transaction)
signed_txn = w3.eth.account.sign_transaction(transaction, private_key=private_key)
print(signed_txn) # this is how we sign a transaction
tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
# 1 good practice to do when we are sending
# a transaction is to wait for some block confirmation to happen
# this will have our code stop and wait for this transaction hash to go through
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
# working with contracts
# Contract Address
# Contract ABI
# Working with deployed Contracts
simple_storage = w3.eth.contract(address=tx_receipt.contractAddress, abi=abi)
# call->Simulate making the call and getting a return value
# Transact->Actually make a state change
# Initial value of a favorite number
print(simple_storage.functions.retrieve().call())
# store some value into this contract
store_transaction = simple_storage.functions.store(15).buildTransaction(
{
"chainId": chain_id,
"gasPrice": w3.eth.gas_price,
"from": my_address,
"nonce": nonce
+ 1,
}
)
signed_store_txn = w3.eth.account.sign_transaction(
store_transaction, private_key=private_key
)
send_store_tx = w3.eth.send_raw_transaction(signed_store_txn.rawTransaaction)
tx_receipt = w3.eth.wait_for_transaction_receipt(send_store_tx)
#[1]: https://i.stack.imgur.com/sPikF.png
During handling of the above exception, another exception occurred:
During handling of the above exception, another exception occurred:
During handling of the above exception, another exception occurred:
During handling of the above exception, another exception occurred:
During handling of the above exception, another exception occurred:

Django Content Management System [duplicate]

My setup is Windows 10, Python 3.7, Apache 2.4/mod_wsgi. When I add this enctype="multipart/form-data" in my form (just by adding this attribute, only -- no files are attached to the form) I get this error when submitting:
Django Version: 1.8.5
Exception Type: RuntimeError
Exception Value: generator raised StopIteration
Exception Location: c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\multipartparser.py in read, line 337
Python Executable: C:\Apache24\bin\httpd.exe
Python Version: 3.7.3
My Django code is this:
elif request.method == "POST":
rid = request.POST.get("recipe", "")
title = request.POST.get("title")
content = request.POST.get("content")
tag_names = request.POST.getlist("tags")
image = request.FILES.get("image")
if rid:
recipe = get_object_or_404(FoodRecipe, pk=rid)
else:
recipe = FoodRecipe.objects.create(title=title)
recipe.content = content
recipe.title = title
if image:
recipe.featured = image
for tn in tag_names:
tag, cr = Tag.objects.get_or_create(
name=tn
)
recipe.tags.add(tag)
recipe.save()
And this is full traceback:
Environment:
Request Method: POST
Request URL: http://192.168.1.250/recipes/add/
Django Version: 1.8.5
Python Version: 3.7.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tinymce',
'sekizai',
'sorl.thumbnail',
'recipes',
'guides',
'inbox',
'appdata',
'account',
'customer',
'core')
Installed Middleware:
('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',
'django.middleware.security.SecurityMiddleware',
'account.middleware.PasswordChangeMiddleware.PasswordChangeMiddleware')
Traceback:
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\core\handlers\base.py" in get_response
125. response = middleware_method(request, callback, callback_args, callback_kwargs)
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\middleware\csrf.py" in process_view
174. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\core\handlers\wsgi.py" in _get_post
137. self._load_post_and_files()
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\request.py" in _load_post_and_files
260. self._post, self._files = self.parse_file_upload(self.META, data)
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\request.py" in parse_file_upload
225. return parser.parse()
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\multipartparser.py" in parse
149. for item_type, meta_data, field_stream in Parser(stream, self._boundary):
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\multipartparser.py" in __iter__
628. yield parse_boundary_stream(sub_stream, 1024)
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\multipartparser.py" in parse_boundary_stream
567. chunk = stream.read(max_header_size)
File "c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\multipartparser.py" in read
337. out = b''.join(parts())
Exception Type: RuntimeError at /recipes/add/
Exception Value: generator raised StopIteration
Any ideas what is going wrong?
PS: Same django application worked fine in Linux/Nginx/Gunicorn/Python2.7 setup. So, I guess it must some misconfiguration between Django/Python/Apache.
Your Django is very old and you need to update. This is a Python 3.7 compatibility problem that the Django devs already fixed four years ago, back when it was just a PendingDeprecationWarning on Python 3.5.
In fact, you are on the very last Django version that doesn't have the fix. Even 1.8.6 has the fix.

I have problem reset password in django . My error is 'availabe Apps' key error

Firstly I call:
from django.contrib.auth import views as auth_views
After that I have set the url:
path('reset_password/',auth_views.PasswordResetView.as_view(),name='reset_password'),
When I run the url the key error raised.
Request Method: GET
Request URL: http://127.0.0.1:8000/user/reset_password/
Django Version: 3.1
Exception Type: KeyError
Exception Value:
'available_apps'
Exception Location: C:\Users\Syed Mithu\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\context.py, line 83, in __getitem__
Python Executable: C:\Users\Syed Mithu\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.3
Python Path:
['F:\\12.05.2021\\Project\\Music_E-com',
'C:\\Users\\Syed '
'Mithu\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\Syed Mithu\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\Syed Mithu\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\Syed Mithu\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\Syed '
'Mithu\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages',
'C:\\Users\\Syed '
'Mithu\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32',
'C:\\Users\\Syed '
'Mithu\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32\\lib',
'C:\\Users\\Syed '
'Mithu\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\Pythonwin']
Server time: Thu, 20 May 2021 06:51:41 +0000

Django ORM filter on bool field not permitted

i have my django models:
class p_linea(models.Model):
l_name = models.CharField(max_length=100, verbose_name="Linea")
l_pubblica = models.BooleanField(default=False, verbose_name="Pubblica")
l_note = models.TextField(null=True, blank=True, verbose_name="Note interne")
class Meta:
verbose_name = "Linea"
verbose_name_plural = "Linee"
def __str__(self):
return '%s' % (
str(self.l_name))
class p_catlinea(models.Model):
p_lid = models.ForeignKey(p_linea, on_delete=models.CASCADE, verbose_name="Linea")
p_cid = models.ForeignKey(p_catl, on_delete=models.CASCADE, verbose_name="Categoria")
l_note = models.TextField(null=True, blank=True, verbose_name="Note interne")
dt = models.DateTimeField(auto_now=True, verbose_name="Upload")
class Meta:
indexes = [
models.Index(fields=['p_cid','p_lid']),
]
verbose_name = "Linea/Categoria"
verbose_name_plural = "Linea/Categoria"
def __str__(self):
return '%s' % (
str(self.p_cid))
now in my views.py i try to filter p_catliea baset on the fact that p_linea.l_pubblica is True, i try:
...
p_cl = p_catlinea.objects.all().select_related()
for x in p_cl:
if x.p_lid.l_pubblica:
try:
l_lincat[str(x.p_lid)]['cat'] = get_cat(x.p_lid_id)
except KeyError:
l_lincat[str(x.p_lid)] = {'cat': get_cat(x.p_lid_id),}
but i got error:
'bool' object is not callable
even if i di x.p_lid.l_pubblica == True i got the same error.
How can i filter my data based on True or Fale of related table field?
this is the full error:
TypeError at /prodotti/
'bool' object is not callable
Request Method: GET
Request URL: http://127.0.0.1:8000/prodotti/
Django Version: 3.0.5
Exception Type: TypeError
Exception Value:
'bool' object is not callable
Exception Location: /home/kngmalza/BIGDATA/Project/tebiskin/tebiskin/prodotti/views.py in f_prodotti, line 24
Python Executable: /usr/bin/python3
Python Version: 3.8.2
Python Path:
['/home/kngmalza/BIGDATA/Project/tebiskin/tebiskin',
'/usr/lib/python38.zip',
'/usr/lib/python3.8',
'/usr/lib/python3.8/lib-dynload',
'/home/kngmalza/.local/lib/python3.8/site-packages',
'/usr/local/lib/python3.8/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Tue, 23 Jun 2020 06:50:35 +0000
So many thanks in advance

Abnormal behavior of python package eve

I have installed the eve package on my windows machine but every time I shutdown the machine and try to load the eve package I get module not found error.
On re-installation attempt(Btw I used the latest pip version to install), I get
from eve import Eve
app=Eve()
app.run()
The error points to the second line.
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-79-46d1b24866c8> in <module>()
30 # host = '127.0.0.1'
31
---> 32 app = Eve()
33 # app.run()
34
~\AppData\Local\Continuum\anaconda3\lib\site-packages\eve\flaskapp.py in __init__(self, import_name, settings, validator, data, auth, redis, url_converters, json_encoder, media, **kwargs)
158 self.settings = settings
159
--> 160 self.load_config()
161 self.validate_domain_struct()
162
~\AppData\Local\Continuum\anaconda3\lib\site-packages\eve\flaskapp.py in load_config(self)
275
276 try:
--> 277 self.config.from_pyfile(pyfile)
278 except:
279 raise
~\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\config.py in from_pyfile(self, filename, silent)
128 try:
129 with open(filename, mode='rb') as config_file:
--> 130 exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
131 except IOError as e:
132 if silent and e.errno in (
~\AppData\Local\Continuum\anaconda3\lib\site-packages\bokeh\settings.py in <module>()
9 from os.path import join, abspath, isdir
10
---> 11 from .util.paths import ROOT_DIR, bokehjsdir
12
13
ModuleNotFoundError: No module named 'config'
Moreover, I find that there is no folder "lib" but "Lib". If this is the problem how do I rectify it?
However, the code below works but runs for microsecs, not like running a back-end server with api's:
from eve import Eve
app=Eve
app.run
The settings.py file:
# Let's just use the local mongod instance. Edit as needed.
# Please note that MONGO_HOST and MONGO_PORT could very well be left
# out as they already default to a bare bones local 'mongod' instance.
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_DBNAME = 'apitest'
# Enable reads (GET), inserts (POST) and DELETE for resources/collections
# (if you omit this line, the API will default to ['GET'] and provide
# read-only access to the endpoint).
RESOURCE_METHODS = ['GET', 'POST', 'DELETE']
# Enable reads (GET), edits (PATCH), replacements (PUT) and deletes of
# individual items (defaults to read-only item access).
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
people = {
# 'title' tag used in item links.
'item_title': 'person',
# by default the standard item entry point is defined as
# '/people/<ObjectId>/'. We leave it untouched, and we also enable an
# additional read-only entry point. This way consumers can also perform GET
# requests at '/people/<lastname>/'.
'additional_lookup': {
'url': 'regex("[\w]+")',
'field': 'lastname'
},
'cache_control': 'max-age=10,must-revalidate',
'cache_expires': 10,
'resource_methods': ['GET', 'POST'],
# Schema definition, based on Cerberus grammar. Check the Cerberus project
# (https://github.com/pyeve/cerberus) for details.
'schema': {
'firstname': {
'type': 'string',
'minlength': 1,
'maxlength': 10,
},
'lastname': {
'type': 'string',
'minlength': 1,
'maxlength': 15,
'required': True,
# talk about hard constraints! For the purpose of the demo
# 'lastname' is an API entry-point, so we need it to be unique.
'unique': True,
},
# 'role' is a list, and can only contain values from 'allowed'.
'role': {
'type': 'list',
'allowed': ["author", "contributor", "copy"],
},
# An embedded 'strongly-typed' dictionary.
'location': {
'type': 'dict',
'schema': {
'address': {'type': 'string'},
'city': {'type': 'string'}
},
},
'born': {
'type': 'datetime',
},
}
}
DOMAIN = {
'people': people,
}
So, What could be the solution to this problem?
Any help is appreciated.
I don't have this issue after a quick test. Let me share with you all steps and let me know anything is different.
1) Enter Anaconda Prompt
2) conda create -n eswar python=3.6
3) conda activate eswar
4) pip install eve
5) python
5.1) import eve
5.2) exit()
6) shutdown windows machine
7) restart windows machine
8) enter anaconda prompt
9) conda activate eswar
10) python
11) from eve import Eve
12) everything looks fine.
did you forget to activate your env after restart?

Resources