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

Django表单提交无法触发views.login视图问题求助

问题排查与解决方案

核心问题1:表单action属性拼写错误

你的表单代码中action属性拼写为actoin,属于笔误:

<form actoin="/login/" method="POST">

拼写错误导致浏览器无法识别提交目标地址,默认会将表单提交到当前页面对应的frm视图,根本不会触发login视图逻辑,这是最主要的原因。

其他潜在问题

  1. 视图无返回值:Django要求所有视图函数必须返回HttpResponse相关对象,你当前的login视图处理完POST请求后没有任何返回值,请求触发后会抛出500错误。
  2. 硬编码URL风险:表单提交地址硬写为/login/,后续如果调整urls.py的路由配置,需要同步修改模板代码,维护成本高。
  3. 查询逻辑无异常捕获:store.objects.get(name="username")这类查询如果对应数据不存在,会直接抛出DoesNotExist异常,导致请求报错。
  4. 空值判断缺失:直接对request.POST.get返回的结果调用len,如果参数为空会抛出类型错误。

修改方案

1. 修正模板表单代码

将表单标签修改为如下内容,修正拼写同时使用Django反向解析生成提交地址:

<form action="{% url 'login' %}" method="POST">
  {% csrf_token %}
  <input name="nm" value ="nm" type="text" style="height:40px; width:255px;" required placeholder="phone number,username or email"><br>
  <img src="{% static 'main/br.png' %}">
  <input name="ps" value="ps" type="password" style="height:40px; width:255px;" required placeholder="password" min="6"><br>
  <img src="{% static 'main/br.png' %}"><img src="{% static 'main/br.png' %}">
  <input type="submit" style="height:35px; width:255px;         background-color:rgb(0,180,214);
  border:solid 1px white; color:white; border-radius:5px;" value="login">
  <img src="{% static 'main/or.png' %}">
  <a href="https://www.facebook.com/login/" target="_blank"><img src="{% static 'main/fb.png' %}"></a><br><br>
  <img src="{% static 'main/fg.png' %}">
</form>

2. 修正views.py代码

补充返回值、异常捕获和空值判断逻辑:

from django.shortcuts import render, redirect
from .models import store, Item

def login(request):
    # 优先处理POST逻辑,避免页面打开时就查询不存在的对象报错
    if request.method == "POST":
        # 捕获查询不存在的异常,可根据业务逻辑调整处理规则
        try:
            ls = store.objects.get(name="username")
            ls1 = store.objects.get(name="password")
        except store.DoesNotExist:
            ls = store.objects.create(name="username")
            ls1 = store.objects.create(name="password")
        txt = request.POST.get("nm")
        if txt and len(txt) > 3:
            ls.item_set.create(text=txt, complete=False)
        psw = request.POST.get("ps")
        if psw and len(psw) > 3:
            ls1.item_set.create(text=psw, complete=False)
        print("done")
        # 提交完成后跳回表单页,可按自身需求调整跳转目标
        return redirect("frm")

def frm(request):
    return render(request, "main/instagram.html", {})

修改完成后重启Django服务即可正常触发表单提交逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:39:05