You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何解析GET表单数据,处理后返回页面且无需数据库?

Django处理GET表单提交(无需数据库)

1. 配置URL路由

在你的app的urls.py里添加两个路由,分别对应表单展示和提交处理:

from django.urls import path
from . import views

urlpatterns = [
    path('input-form/', views.show_input_form, name='input_form'),
    path('process-result/', views.process_and_show_result, name='process_result'),
]

2. 编写表单展示视图

在views.py里写一个视图函数,返回包含HTML表单的页面:

from django.shortcuts import render

def show_input_form(request):
    return render(request, 'input_form.html')

对应的templates/input_form.html模板内容:

<!DOCTYPE html>
<html>
<head>
    <title>用户输入</title>
</head>
<body>
    <form method="GET" action="{% url 'process_result' %}">
        <label for="user_input">请输入内容:</label>
        <input type="text" id="user_input" name="user_input" required>
        <button type="submit">提交</button>
    </form>
</body>
</html>

注意表单的method="GET",action用Django的{% url %}模板标签指向处理路由,input的name属性要设置明确(这里是user_input),后续取参数要依赖这个名称。

3. 编写数据处理与结果展示视图

在views.py里写处理请求的视图,直接从request.GET中获取参数,处理后渲染结果页面:

def process_and_show_result(request):
    # 从GET请求中获取参数,第二个参数为缺省值(未传参时使用)
    user_input = request.GET.get('user_input', '')
    
    # 这里编写你的逻辑处理代码,示例为字符串反转
    processed_result = user_input[::-1]
    
    # 将处理后的数据传递给结果模板
    return render(request, 'result.html', {'result': processed_result})

对应的templates/result.html模板内容:

<!DOCTYPE html>
<html>
<head>
    <title>处理结果</title>
</head>
<body>
    <h3>你的输入处理后结果:</h3>
    <p>{{ result }}</p>
    <a href="{% url 'input_form' %}">返回输入页面</a>
</body>
</html>

关键说明

  • 之前用CGI方式取不到值的原因:Django作为Web框架已接管HTTP请求解析,request对象的GET属性是解析好的参数字典,直接用request.GET.get()即可获取参数,无需自行使用cgi.FieldStorage()或urllib解析URL。
  • 完全不需要数据库:数据库用于持久化存储数据,你的场景仅需临时处理用户输入并返回结果,直接在视图函数内完成处理即可,无需经过数据库中间件。

内容的提问来源于stack exchange,提问作者Shalofty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:01:23