Just recently, I discovered how to set up a web server on a Raspberry Pi using Django. I'm in the process of enhancing it by integrating JS to generate a form every time data is sent. However, I've encountered an error that I haven't been able to resolve yet. Any assistance would be greatly appreciated.
When running the web server, here's the error I come across: view error image here
Below is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>blablablai</title>
<script>
function sendDirection(direction) {
const data = new FormData();
data.append('direction', direction);
const request = new XMLHttpRequest();
request.open('POST', '{% url "home" %}');
request.send(data);
}
function onMouseDown(direction) {
sendDirection(direction);
}
function onMouseUp() {
sendDirection('stop');
}
</script>
</head>
<body>
<h1>bzzzz....</h1>
<button type="button" onmousedown="onMouseDown('forward')" onmouseup="onMouseUp()">Forward</button>
<button type="button" onmousedown="onMouseDown('backward')" onmouseup="onMouseUp()">Backward</button>
<button type="button" onmousedown="onMouseDown('left')" onmouseup="onMouseUp()">Left</button>
<button type="button" onmousedown="onMouseDown('right')" onmouseup="onMouseUp()">Right</button>
<form method="post" action="{% url 'change_speed' %}">
{% csrf_token %}
<button type="submit" name="speed" value="25">Speed 25%</button>
<button type="submit" name="speed" value="50">Speed 50%</button>
<button type="submit" name="speed" value="75">Speed 75%</button>
<button type="submit" name="speed" value="100">Speed 100%</button>
</form>
</body>
</html>
Also, here's a snippet from my views.py file:
from django.shortcuts import render, redirect
import smbus
# Define I2C address
SLAVE_ADDRESS = 0x27
# Initialize I2C bus
bus = smbus.SMBus(1)
# Define motor control functions
def forward():
bus.write_byte(SLAVE_ADDRESS, ord('f'))
# Other motor control functions omitted for brevity
def change_speed(request):
if request.method == 'POST':
speed = request.POST.get('speed')
# Determine speed level chosen
if speed == '25':
speed25()
elif speed == '50':
speed50()
elif speed == '75':
speed75()
elif speed == '100':
speed100()
return redirect('home')
else:
return render(request, 'home.html')
As a beginner in Django, I've consulted the official documentation here to resolve my issue, but to no avail. Any guidance on this matter would be highly appreciated!