Create A New Django Project Named Calculator
Create A New Django Project Named Calculator
cd calculator_project
Configure settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
urlpatterns = [
path('admin/', admin.site.urls),
]
Step 5: Create the View Function
Edit calculator/views.py:
def calculator(request):
result = None
if request.method == "POST":
num1 = float(request.POST.get("num1"))
num2 = float(request.POST.get("num2"))
operation = request.POST.get("operation")
if operation == "add":
Inside the calculator app, create a templates folder and a file named calculator.html:
calculator/
│── templates/
│ ├── calculator.html
Now, create calculator/templates/calculator.html and add:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Arithmetic Calculator</h2>
<form method="post">
{% csrf_token %}
<label>Number 1:</label>
<label>Number 2:</label>
<label>Operation:</label>
<select name="operation">
</select><br><br>
<button type="submit">Calculate</button>
</form>
{% endif %}
</body>
</html>
app = Flask(__name__)
def calculate_grade(average_marks):
return "A"
return "B"
return "C"
elif average_marks >= 60:
return "D"
else:
return "F"
def grade_calculator():
grade = None
average_marks = None
if request.method == 'POST':
try:
marks = [
float(request.form['subject1']),
float(request.form['subject2']),
float(request.form['subject3']),
float(request.form['subject4']),
float(request.form['subject5'])
# Calculate average
grade = calculate_grade(average_marks)
except ValueError:
if __name__ == '__main__':
app.run(debug=True)
Step 3: Create HTML Template
Inside your Flask project, create a templates/ folder and inside it, create index.html.
grade_calculator/
│── app.py
│── templates/
│ ├── index.html
<!DOCTYPE html>
<html>
<head>
<title>Grade Calculator</title>
</head>
<body>
<form method="post">
<label>Subject 1:</label>
<label>Subject 2:</label>
<label>Subject 3:</label>
<label>Subject 4:</label>
<label>Subject 5:</label>
<input type="number" name="subject5" required><br><br>
</form>
{% if grade %}
{% endif %}
</body>
</html>
python app.py
This will start the server at http://127.0.0.1:5000/. Open the link in a browser.