【问题标题】:NoReverseMatch at 'url' in Django, Reverse for 'my_app' not found. 'my_app' is not a valid view function or pattern nameNoReverseMatch 在 Django 中的“url”,找不到“my_app”的反向。 “my_app”不是有效的视图函数或模式名称
【发布时间】:2021-08-02 20:21:20
【问题描述】:

我是 Django 新手,今天尝试使用数据库运行网站时,遇到了这个错误。 我已经在 StackOverflow 和 Django 文档上搜索了所有解决方案,但我无法修复它。

This is the problem that similar to me, but it doesn't work.

我想创建一个链接,将用户从 user.html in user 移动到 index.html inCitizen

这是我的项目结构。很抱歉,因为我无法附上图片,所以我将尝试以最简单的方式解释它。

[我的项目]

->ma​​nage.py

->公民(文件夹)

-->模板(在这个文件夹中我有citizen.html、index.html、layout.html)

-->admin.py

-->models.py

-->tests.py

-->urls.py

-->views.py

->我的项目(文件夹)

-->setting.py

-->urls.py

-->我认为不重要的东西

->用户(文件夹)

-->模板(在这个文件夹中我有 login.html、user.html、layout.html)

-->urls.py

-->views.py

-->我认为不重要的东西

如您所见,我在用户的模板文件夹中有 user.html,在公民的模板文件夹中有 index.html

这是我的代码:

公民内部的index.html

{% extends "citizens/layout.html" %}

{% block body %}
    <h1>Hệ thống quản lý XNC</h1>
    
    <table class="table">
        
        <thead>
          <tr>
            <th scope="col">Số TT</th>
            <th scope="col">Họ và tên công dân</th>
            <th scope="col">Giới tính</th>
            <th scope="col">Số Hộ chiếu</th>
            <th scope="col">Chi tiết</th>
          </tr>
        </thead>
        <tbody>
          {% for citizen in citizens %}
          <tr>
            <th scope="row">{{ forloop.counter }}</th>
            <td>{{ citizen.name }}</td>
            <td>{{ citizen.sex }}</td>
            <td>{{ citizen.sID }}</td>
            <td><a href="{% url 'citizen' forloop.counter %}">Truy cập</a></td>
          </tr>
          {% endfor %}
        </tbody>
        
    </table>

    
{% endblock %}

user.html 内部用户

{% extends "users/layout.html" %}

{% block body %}

    <h1>Chào mừng, {{ request.user.username }}</h1>

    <ul>
        <li>Username: {{request.user.username }}</li>
    </ul>
    <a href="{% url 'citizen:citizens/' %}">Truy cập Cơ sở dữ liệu</a>
        
{% endblock %}

公民内部的urls.py

from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("<int:citizen_id>", views.citizen, name="citizen"),
    #path("<int:citizen_id>/passports", views.passport, name="passports")
]
    

公民内部的views.py

from django.shortcuts import render
from django.http import HttpResponseBadRequest, HttpResponseRedirect, Http404
from django.urls import reverse

from .models import Citizen 

# Create your views here.
def index(request):
    return render(request, "citizens/index.html", {
        "citizens": Citizen.objects.all()
    })

def citizen(request, citizen_id):
    try:
        citizen = Citizen.objects.get(sID=citizen_id)
    except Citizen.DoesNotExist:
        raise Http404("Citizen not found")
    return render(request, "citizens/citizen.html", {
        "citizen": citizen,
        
        
    })


我的项目中的urls.py

"""htql2 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('citizens/', include('citizens.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
    path('users/', include('users.urls')),
]

用户内部的urls.py

from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    
]
    

views.py 内部用户

from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render
from django.http import HttpResponseBadRequest, HttpResponseRedirect, Http404
from django.urls import reverse

@csrf_exempt

# Create your views here.
def index(request):
    if not request.user.is_authenticated:
        return HttpResponseRedirect(reverse("login"))
    return render(request, "users/user.html")    

def login_view(request):
    if request.method == "POST":
        username = request.POST["username"]
        password = request.POST["password"]
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return HttpResponseRedirect(reverse("index"))
        else:
            return render(request, "users/login.html", {
                "message": "Invalid credentials."
            }) 
    else:
        return render(request, "users/login.html")        

def logout_view(request):
    pass

user.html里面,我试过用

<a href="{% url 'citizen:citizens/' %}">Go to Database</a>

但不起作用。

谢谢。我很感激。

【问题讨论】:

  • "my_app" 仅在一 (1) 块代码中定义。为什么要包含所有其他代码块?

标签: html python-3.x django


【解决方案1】:

您尝试使用{% url 'citizen:citizens/' %},这里: (citizen) 之前的部分是一个url 命名空间,它之后的部分(citizens) 是url 名称。但是你没有使用任何命名空间,也没有citizens这样的url名称。

您可以通过指定app_namecitizens.urls 中添加命名空间:

from django.urls import path

from . import views

app_name = 'citizens' # here
urlpatterns = [
    path("", views.index, name="index"),
    path("<int:citizen_id>", views.citizen, name="citizen"),
    #path("<int:citizen_id>/passports", views.passport, name="passports")
]

接下来需要将url标签写成{% url 'citizens:index' %}:

<a href="{% url 'citizens:index' %}">Go to Database</a>

【讨论】:

猜你喜欢
  • 2019-04-21
  • 2019-08-13
  • 2019-05-19
  • 2018-01-25
  • 2019-06-27
  • 2019-06-01
  • 2018-11-29
  • 2021-07-18
  • 1970-01-01
相关资源
最近更新 更多