在django中实现一个网页来计算两个数字的和

以下是如何在 Django 中实现一个网页来计算两个数字的和,并在后台处理计算过程的详细步骤:

1. 创建 Django 项目和应用

首先,在你的 Django 项目中创建一个新的应用,例如 calculator

sh

django-admin startproject myproject
cd myproject
python manage.py startapp calculator

2. 配置 Django 项目

2.1 修改 settings.py

在 settings.py 中,将新创建的应用 calculator 添加到 INSTALLED_APPS 列表中:

python

INSTALLED_APPS = [
    ...
    'calculator',
]

2.2 修改 urls.py

在项目的 urls.py 中,将根 URL 映射到 calculator 应用:

python

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('calculator.urls')),  # 将根 URL 映射到 calculator 应用
]

3. 创建 calculator 应用的 URL 和视图

3.1 创建 calculator/urls.py

在 calculator 应用目录中创建 urls.py 文件,并设置 URL 路由:

python

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),  # 设置首页
    path('calculate/', views.calculate, name='calculate'),  # 设置计算路径
]

3.2 创建 calculator/views.py

在 calculator/views.py 中创建视图函数:

python

from django.shortcuts import render
from django.http import JsonResponse

def index(request):
    return render(request, 'calculator/index.html')

def calculate(request):
    if request.method == 'POST':
        a = int(request.POST.get('a', 0))
        b = int(request.POST.get('b', 0))
        result = a + b
        return JsonResponse({'result': result})
    return JsonResponse({'error': 'Invalid request'}, status=400)

4. 创建模板

4.1 创建模板目录

在 calculator 应用目录下创建 templates/calculator/ 目录:

sh

mkdir -p calculator/templates/calculator

4.2 创建 calculator/templates/calculator/index.html

创建 index.html 文件,并编写前端代码:

html

<!DOCTYPE html>
<html>
<head>
    <title>Calculator</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Calculator</h1>
    <form id="calculator-form">
        <label for="a">Enter number a:</label>
        <input type="number" id="a" name="a" required>
        <br>
        <label for="b">Enter number b:</label>
        <input type="number" id="b" name="b" required>
        <br>
        <button type="submit">Calculate</button>
    </form>
    <h2>Result: <span id="result"></span></h2>

    <script>
        $(document).ready(function(){
            $('#calculator-form').on('submit', function(event){
                event.preventDefault();
                $.ajax({
                    url: "{% url 'calculate' %}",
                    type: "POST",
                    data: {
                        'a': $('#a').val(),
                        'b': $('#b').val(),
                        'csrfmiddlewaretoken': '{{ csrf_token }}'
                    },
                    success: function(response){
                        $('#result').text(response.result);
                    },
                    error: function(response){
                        $('#result').text('Error');
                    }
                });
            });
        });
    </script>
</body>
</html>

5. 配置 CSRF 中间件

确保你的 settings.py 中包含 CSRF 中间件:

python

MIDDLEWARE = [
    ...
    'django.middleware.csrf.CsrfViewMiddleware',
    ...
]

6. 运行 Django 开发服务器

在终端中,导航到你的项目目录,并运行 Django 开发服务器:

sh

python manage.py runserver

现在,你可以访问 http://127.0.0.1:8000 来查看你的计算器网页。输入两个数字,点击“Calculate”按钮,结果会在页面上显示。

  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,根据你的需求,我可以为你提供一个简单的实现方案: 1. 创建一个名为 "sum_app" 的 Django 应用程序。 2. 在 "sum_app" 应用程序下的 "models.py" 文件定义一个名为 "Number" 的模型,代码如下: ``` from django.db import models class Number(models.Model): num1 = models.IntegerField() num2 = models.IntegerField() ``` 3. 在 "sum_app" 应用程序下的 "views.py" 文件定义一个名为 "calculate_sum" 的视图函数,代码如下: ``` from django.shortcuts import render from django.db import connection from .models import Number def calculate_sum(request): if request.method == 'POST': num1 = request.POST.get('num1') num2 = request.POST.get('num2') # 将 num1 和 num2 存入数据 Number.objects.create(num1=num1, num2=num2) # 使用 SQL 查询计算和 with connection.cursor() as cursor: cursor.execute("SELECT num1 + num2 FROM sum_app_number ORDER BY id DESC LIMIT 1") result = cursor.fetchone()[0] context = {'result': result} return render(request, 'sum_app/result.html', context) return render(request, 'sum_app/index.html') ``` 4. 在 "sum_app" 应用程序下的 "urls.py" 文件定义一个名为 "calculate_sum" 的 URL,代码如下: ``` from django.urls import path from . import views urlpatterns = [ path('', views.calculate_sum, name='calculate_sum'), ] ``` 5. 在 "sum_app" 应用程序下的 "templates" 文件夹创建两个 HTML 文件,分别为 "index.html" 和 "result.html",代码如下: index.html: ``` <!DOCTYPE html> <html> <head> <title>Calculate Sum</title> </head> <body> <h1>Enter two numbers to calculate their sum:</h1> <form method="post"> {% csrf_token %} <label for="num1">Number 1:</label> <input type="number" name="num1" id="num1"> <br> <label for="num2">Number 2:</label> <input type="number" name="num2" id="num2"> <br> <input type="submit" value="Calculate Sum"> </form> </body> </html> ``` result.html: ``` <!DOCTYPE html> <html> <head> <title>Sum Result</title> </head> <body> <h1>The sum of the two numbers is:</h1> <p>{{ result }}</p> </body> </html> ``` 6. 最后,在项目的 "urls.py" 文件包含 "sum_app" 应用程序的 URL 配置,代码如下: ``` from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('sum_app.urls')), ] ``` 这样,当用户访问应用程序的首页时,将会看到一个表单,要求输入两个数字。当用户提交表单后,将会计算两个数字的和,并显示在另一个页面上。计算和的过程使用了 SQL 查询,从数据获取最新的两个数字计算它们的和
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值