Estoy haciendo mi primer página en Django para practicar. Es una calculadora web donde podés anotar un detalles en las operaciones, estas se guardan, y además pueden modificarse o eliminarse.
Aún no resolví la cuestión de modificar la "Operations List", por eso todavía no habilité la función de eliminar. Todavía no tiene estilos.
Por favor les pido que me ayuden con cualquier idea, opinión, colaboración que tengan.
Este es el código...
views.py: La web carga bien, la función "calculate" pareciera no tener problemas. Aunque desde el principio la consola CMD tira errores, por más que la página funcione. El lío empieza en "modify_operations"
#views.py - Directorio: C:\Projects\test\NoteCalc0.2\myapp\views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
def calculate(request):
if request.method == 'GET':
request.session.flush()
if request.method == 'POST':
expression = request.POST.get('expression', '')
detail = request.POST.get('detail', '')
try:
result = eval(expression)
if 'operations' not in request.session:
request.session['operations'] = []
operations = request.session['operations']
operations.insert(0, (expression, result, detail)) #operations.append((expression, result, detail))
request.session['operations'] = operations
total = sum([op[1] for op in operations])
print(operations)
return render(request, 'calculator/index.html', {'result': result, 'operations': operations, 'total': total})
except:
operations = request.session.get('operations', [])
total = sum([x[1] for x in operations])
return render(request, 'calculator/index.html', {'result': 'Error', 'expression': expression, 'operations': operations, 'total': total, 'detail': detail})
else:
return render(request, 'calculator/index.html', {'result': ''})
def clear_history(request):
request.session['operations'] = []
return redirect('/')
def modify_operation(request):
if request.method == 'POST':
expression = request.POST.get('expression')
detail = request.POST.get('detail')
operations = request.session.get('operations')
operation_id = int(request.POST.get('operation_id'))
result = eval(str(expression))
operations[int(operation_id)] = (expression, result, detail)
#int(sum([int(r[1]) for r in operations]))
total = request.POST.get('total')
request.session['operations'] = operations
return render(request, 'calculator/index.html', {'result': result, 'operations': operations, 'total': total})
index.html: El problema empieza a partir de Operations List. No sé si el error está en cómo se asignan las variables en la plantilla, o cómo se procesan en el servidor con "modify_operation". LLegué a un punto donde quedé perdido. Lamentablemente la consola de comandos tira tantos errores que no se pueden hacer prints() para ir controlando el código línea por línea.
#index.html - Directorio: C:\Projects\test\NoteCalc0.2\templates\calculator\index.html
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form action="/" method="post">
{% csrf_token %}
<input type="text" name="expression" value="{% if result == 'Error' %}{{ expression }}{% endif %}">
<input type="text" name="detail" value="{% if result == 'Error' %}{{ detail }}{% endif %}">
<input type="submit" value="Calculate">
<br><br>
<input type="button" value="1" onclick="document.forms[0].expression.value+='1'">
<input type="button" value="2" onclick="document.forms[0].expression.value+='2'">
<input type="button" value="3" onclick="document.forms[0].expression.value+='3'">
<input type="button" value="+" onclick="document.forms[0].expression.value+='+'">
<br>
<input type="button" value="4" onclick="document.forms[0].expression.value+='4'">
<input type="button" value="5" onclick="document.forms[0].expression.value+='5'">
<input type="button" value="6" onclick="document.forms[0].expression.value+='6'">
<input type="button" value="-" onclick="document.forms[0].expression.value+='-'">
<br>
<input type="button" value="7" onclick="document.forms[0].expression.value+='7'">
<input type="button" value="8" onclick="document.forms[0].expression.value+='8'">
<input type="button" value="9" onclick="document.forms[0].expression.value+='9'">
<input type="button" value="*" onclick="document.forms[0].expression.value+='*'">
<br>
<input type="button" value="C" onclick="document.forms[0].expression.value=''">
<input type="button" value="0" onclick="document.forms[0].expression.value+='0'">
<input type="button" value="=" onclick="document.forms[0].submit()">
<input type="button" value="/" onclick="document.forms[0].expression.value+='/'">
</form>
{% if result %}
<h3>Result: {{ result }}</h3>
{% endif %}
<h2>Total: {{ total }}</h2>
<form action="{% url 'clear_history' %}" method="post">
{% csrf_token %}
<input type="submit" value="Clear History">
</form>
<h2>Operations List:</h2>
<form action="/modify_operation/" method="post">
{% csrf_token %}
<table>
<thead>
<tr>
<th>ID</th>
<th>Operation</th>
<th>Result</th>
<th>Detail</th>
</tr>
</thead>
<tbody>
{% for expression, result, detail in operations %}
<tr>
<td><p type="text">{{ forloop.counter }}</p></td>
<td><input type="text" name="expression-{{ forloop.counter }}" value="{{ expression }}"></td>
<td><p type="text" name="result-{{ forloop.counter }}">{{ result }}</p></td>
<td><input type="text" name="detail-{{ forloop.counter }}" value="{{ detail }}"></td>
<td><button action="{% url 'modify_operation' %}" name="operation_id" value={{ forloop.counter0 }}>Modify</button></td>
<td>Delete</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
<script>
const input = document.querySelector('input[name="expression"]');
input.focus();
input.setSelectionRange(input.value.length, input.value.length);
</script>
</body>
</html>
urls.py: También está el urls.py de mysite que redirige a este archivo de urls.
#urls.py - Directorio: C:\Projects\test\NoteCalc0.2\myapp\urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.calculate, name='calculate'),
path('clear_history/', views.clear_history, name='clear_history'),
path('modify_operation/', views.modify_operation, name='modify_operation'),
]
Modificando los "name" de los input, sucede que a cualquier valor que modifique, le asigna los valores de la operación listada debajo de todo.
Esta es la parte en el index.html:
<tbody>
{% for expression, result, detail in operations %}
<tr>
<td><p type="text">{{ forloop.counter }}</p></td>
<td><input type="text" name="expression" value="{{ expression }}"></td>
<td><p type="text" name="result">{{ result }}</p></td>
<td><input type="text" name="detail" value="{{ detail }}"></td>
<td><button action="{% url 'modify_operation' %}" name="operation_id" value={{ forloop.counter0 }}>Modify</button></td>
<td>Delete</td>
</tr>
{% endfor %}
</tbody>
Esta es la función en views.py:
def modify_operation(request):
if request.method == 'POST':
expression = request.POST.get('expression')
detail = request.POST.get('detail')
operations = request.session.get('operations')
operation_id = int(request.POST.get('operation_id'))
result = eval(str(expression))
operations[int(operation_id)] = (expression, result, detail)
#int(sum([int(r[1]) for r in operations]))
total = request.POST.get('total')
request.session['operations'] = operations
return render(request, 'calculator/index.html', {'result': result, 'operations': operations, 'total': total, 'detail': detail})
ESTO ES LO QUE MUESTRA LA CONSOLA: (ES BASTANTE ILEGIBLE)
AL INICIAR EL SERVER:
C:\Projects\test\NoteCalc0.3>python manage.py runserver
Watching for file changes with StatReloader
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
February 17, 2023 - 15:37:26
Django version 2.2.3, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
AL INTRODUCIR LOS PRIMEROS DATOS ("1" y "a")
[17/Feb/2023 15:38:23] "GET / HTTP/1.1" 200 3001
[('1', 1, 'a')]
[17/Feb/2023 15:38:33] "POST / HTTP/1.1" 200 3499
Traceback (most recent call last):
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 138, in run
self.finish_response()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 196, in finish_response
self.close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\core\servers\basehttp.py", line 111, in close
super().close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\simpl
e_server.py", line 38, in close
SimpleHandler.close(self)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 335, in close
self.result.close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\http\response.py", line 252, in close
signals.request_finished.send(sender=self._handler_class)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\dispatch\dispatcher.py", line 173, in send
return [
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\dispatch\dispatcher.py", line 174, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\__init__.py", line 57, in close_old_connections
conn.close_if_unusable_or_obsolete()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\base\base.py", line 514, in close_if_unusable_or_obsolete
self.close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\sqlite3\base.py", line 248, in close
if not self.is_in_memory_db():
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\sqlite3\base.py", line 367, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'WindowsPath' is not iterable
[17/Feb/2023 15:38:33] "POST / HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 60985)
Traceback (most recent call last):
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 138, in run
self.finish_response()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 196, in finish_response
self.close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\core\servers\basehttp.py", line 111, in close
super().close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\simpl
e_server.py", line 38, in close
SimpleHandler.close(self)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 335, in close
self.result.close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\http\response.py", line 252, in close
signals.request_finished.send(sender=self._handler_class)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\dispatch\dispatcher.py", line 173, in send
return [
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\dispatch\dispatcher.py", line 174, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\__init__.py", line 57, in close_old_connections
conn.close_if_unusable_or_obsolete()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\base\base.py", line 514, in close_if_unusable_or_obsolete
self.close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\sqlite3\base.py", line 248, in close
if not self.is_in_memory_db():
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\sqlite3\base.py", line 367, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'WindowsPath' is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\socketserver.
py", line 650, in process_request_thread
self.finish_request(request, client_address)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\socketserver.
py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\socketserver.
py", line 720, in __init__
self.handle()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\core\servers\basehttp.py", line 171, in handle
self.handle_one_request()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\core\servers\basehttp.py", line 194, in handle_one_request
handler.run(self.server.get_app())
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 145, in run
self.handle_error()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\core\servers\basehttp.py", line 116, in handle_error
super().handle_error()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 382, in handle_error
self.finish_response()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 184, in finish_response
self.write(data)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 288, in write
self.send_headers()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 345, in send_headers
if not self.origin_server or self.client_is_modern():
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 358, in client_is_modern
return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable
----------------------------------------
AL INTRODUCIR LOS SEGUNDOS DATOS ("2" y "b"):
[('2', 2, 'b'), ['1', 1, 'a']]
[17/Feb/2023 15:40:25] "POST / HTTP/1.1" 200 3968
Traceback (most recent call last):
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 138, in run
self.finish_response()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 196, in finish_response
self.close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\core\servers\basehttp.py", line 111, in close
super().close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\simpl
e_server.py", line 38, in close
SimpleHandler.close(self)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 335, in close
self.result.close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\http\response.py", line 252, in close
signals.request_finished.send(sender=self._handler_class)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\dispatch\dispatcher.py", line 173, in send
return [
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\dispatch\dispatcher.py", line 174, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\__init__.py", line 57, in close_old_connections
conn.close_if_unusable_or_obsolete()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\base\base.py", line 514, in close_if_unusable_or_obsolete
self.close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\sqlite3\base.py", line 248, in close
if not self.is_in_memory_db():
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\sqlite3\base.py", line 367, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'WindowsPath' is not iterable
[17/Feb/2023 15:40:25] "POST / HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 60992)
Traceback (most recent call last):
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 138, in run
self.finish_response()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 196, in finish_response
self.close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\core\servers\basehttp.py", line 111, in close
super().close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\simpl
e_server.py", line 38, in close
SimpleHandler.close(self)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 335, in close
self.result.close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\http\response.py", line 252, in close
signals.request_finished.send(sender=self._handler_class)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\dispatch\dispatcher.py", line 173, in send
return [
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\dispatch\dispatcher.py", line 174, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\__init__.py", line 57, in close_old_connections
conn.close_if_unusable_or_obsolete()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\base\base.py", line 514, in close_if_unusable_or_obsolete
self.close()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\sqlite3\base.py", line 248, in close
if not self.is_in_memory_db():
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\sqlite3\base.py", line 367, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'WindowsPath' is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\socketserver.
py", line 650, in process_request_thread
self.finish_request(request, client_address)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\socketserver.
py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\socketserver.
py", line 720, in __init__
self.handle()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\core\servers\basehttp.py", line 169, in handle
self.handle_one_request()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\core\servers\basehttp.py", line 194, in handle_one_request
handler.run(self.server.get_app())
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 145, in run
self.handle_error()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\site-packages
\django\core\servers\basehttp.py", line 116, in handle_error
super().handle_error()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 382, in handle_error
self.finish_response()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 184, in finish_response
self.write(data)
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 288, in write
self.send_headers()
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 345, in send_headers
if not self.origin_server or self.client_is_modern():
File "C:\Users\BCH\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handl
ers.py", line 358, in client_is_modern
return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable
----------------------------------------
Y NO ENTRAN MÁS CARACTERES.