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

Django类认证视图登录页触发NoReverseMatch报错该如何解决?

问题根因

你当前的account/urls.py中没有配置命名为register的URL路由,也没有对应的注册视图实现,login.html模板里调用{% url "register" %}时找不到对应路由就会抛出这个错误,和Django 3.2.6的版本无关。

修复方案

你可以二选一执行:

  • 如果暂时不需要注册功能,直接删除login.html里的<a href="{% url "register" %}">此处注册</a>这段代码,即可快速解决报错。
  • 如果需要保留注册功能,按以下步骤完成配置:

    步骤1:添加注册视图

    在account/views.py中补充注册逻辑:
    from django.shortcuts import render, redirect
    from django.contrib.auth import authenticate, login
    from django.contrib.auth.forms import UserCreationForm
    
    def register(request):
        if request.method == 'POST':
            user_form = UserCreationForm(request.POST)
            if user_form.is_valid():
                new_user = user_form.save(commit=False)
                new_user.set_password(user_form.cleaned_data['password1'])
                new_user.save()
                user = authenticate(username=new_user.username, password=user_form.cleaned_data['password1'])
                login(request, user)
                return redirect('dashboard')
        else:
            user_form = UserCreationForm()
        return render(request, 'account/register.html', {'user_form': user_form})
    

    步骤2:配置register路由

    在account/urls.py的urlpatterns中新增注册路由条目:
    urlpatterns = [
        path('', views.dashboard, name = 'dashboard'),
        path('login/', auth_views.LoginView.as_view(), name = 'login'),
        path('logout/', auth_views.LogoutView.as_view(), name = 'logout'),
        # 新增注册路由
        path('register/', views.register, name='register'),
    ]
    

    步骤3:添加注册模板

    在account/templates/account/路径下新建register.html,内容示例:
    {% extends "base.html" %}
    
    {% block title %}用户注册{% endblock %}
    
    {% block content %}
      <h1>用户注册</h1>
      <p>请使用下方表单完成注册:</p>
      <form method="post">
        {{ user_form.as_p }}
        {% csrf_token %}
        <p><input type="submit" value="注册"></p>
      </form>
    {% endblock %}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:57:00