【问题标题】:Why am I getting a No Reverse Match Error为什么我收到无反向匹配错误
【发布时间】:2021-02-07 15:51:27
【问题描述】:

您好,正在使用 Django 开发一个新站点。似乎无法弄清楚这个错误。首先,预期网站的结构如下:

主页 - 显示不同的语言以及指向您可以学习这些语言的国家/地区的链接。 点击主页上的国家 -> 国家页面 国家页面将列出该国所有教授该语言的学校。 点击国家页面上的学校 -> 学校页面。

我发现国家页面中的这行代码导致了问题,但我不知道如何解决它

<a href="{% url 'schools' schools.id %}">
    <div class="left"><h4>Test Link</h4></div>
</a>

这是我在浏览器中遇到的错误

NoReverseMatch at /5/ Reverse for 'schools' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<country_id>[0-9]+)/(?P<schools_id>[0-9]+)/$']

项目代码: 模型.py

from django.db import models

class Languages(models.Model):
    language = models.CharField(max_length=100, blank=True, null=True)
    country = models.ManyToManyField('Country', blank=True)
    image = models.CharField(max_length=100, blank=True)

    def __str__(self):
        return self.language

class Country(models.Model):
    country_name = models.CharField(max_length=50)
    country_image = models.CharField(max_length=100, blank=True)
    country_city = models.ManyToManyField('City', blank=True)

    def __str__(self):
        return self.country_name

class City(models.Model):
    city_name = models.CharField(max_length=50)
    city_image = models.CharField(max_length=1000, blank=True)
    city_schools_in = models.ManyToManyField('Schools', blank=True)

    def __str__(self):
        return self.city_name

class Schools(models.Model):
    school_name = models.CharField(max_length=100)
    school_image = models.CharField(max_length=1000, blank=True)
    school_country = models.ManyToManyField('Country', blank=True)
    school_city = models.ManyToManyField('City', blank=True)
    school_description = models.TextField()
    school_accreditations = models.ManyToManyField('Accreditations', blank=True)
    school_lpw = models.IntegerField()
    school_cs = models.IntegerField()
    school_course = models.ManyToManyField('CoursePrices', blank=True)

    def __str__(self):
        return self.school_name

class Accreditations(models.Model):
    accreditation_name = models.CharField(max_length=50)

    def __str__(self):
        return self.accreditation_name

class CoursePrices(models.Model):
    course_title = models.CharField(max_length=50, blank=True)
    lessons_per_week = models.IntegerField()
    class_size = models.IntegerField()
    weekly_price =  models.IntegerField()
    language_level = models.CharField(max_length=50, blank=True)

    def __str__(self):
        return self.course_title

Views.py

from django.shortcuts import render
from django.http import Http404

from .models import Schools, CoursePrices, Languages, Country, City


def home(request):
    languages = Languages.objects.all()
    return render(request, 'home.html', {
        'languages': languages,
    })

def country(request, country_id):
    try:
        country = Country.objects.get(id=country_id)
    except Languages.DoesNotExist:
        raise Http404('Language not found')
    return render(request, 'country.html', {
        'country': country,
    })

def schools(request, country_id, schools_id):
    try:
        schools = Schools.objects.get(id=schools_id)
    except Schools.DoesNotExist:
        raise Http404('school not found')
    return render(request, 'schools.html', {
        'schools': schools,
    })

urls.py

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

from schools import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
    path('<int:country_id>/', views.country, name='country'),
    path('<int:country_id>/<int:schools_id>/', views.schools, name='schools'),
]

项目结构截图

任何帮助将不胜感激。也请原谅发布或编码中的任何错误,对于编码和堆栈溢出/生活来说还是很新的:)

【问题讨论】:

    标签: python django django-urls


    【解决方案1】:

    您的名为schools 的路径需要两个参数,您只传递了一个,因此无法匹配任何路由。

    您对 Rafael 的回答的评论,即即使提供了两个参数,它仍然与路径不匹配,这是因为您的 urls.py 文件中的路径顺序。

    Django 将按顺序遍历路径列表,并且因为首先找到具有单个参数 country_id 的路径,它会尝试这样做,但由于您有第二个参数而失败。

    要解决此问题,请更改路径的顺序

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', views.home, name='home'),
        # next two lines have been swapped. 
        path('<int:country_id>/<int:schools_id>/', views.schools, name='schools'),
        path('<int:country_id>/', views.country, name='country'),
    ]
    

    【讨论】:

    • 对不起,你好像比我早 9 秒 xD 为什么人们总是比我快? :( xD
    • @Rafael - 不用担心。我通常对人们在这里回答问题的速度感到惊讶:D
    • @Rafael 不要担心更成熟的答案需要更长时间才能发布。花时间做出一个好的答案,总比匆忙回答要好。
    • 您好,谢谢@Tony 的更新,我已经尝试过您发布的建议(我假设 name='schools'),是用于上述行的末尾吗?)。我似乎仍然无法让它工作。我觉得这可能是我如何实施观点的问题,因为我没有传递正确的学校 ID
    • @SkyFall 谢谢!在查看您的屏幕截图时,我刚刚意识到您的错误:'('',)' 看起来不像整数。您确定schools.id 和country.id 模板变量存在并且是整数吗?
    【解决方案2】:

    “学校”网址需要两 (2) 个参数。您只通过一 (1) 个。在这种情况下:schools.id

    如果你传递了正确数量的参数,Django 只会找到反向匹配。在这种情况下,您应该传递一个国家/地区 ID 和一个学校 ID。

    例如{% url 'schools' country_id=country.id schools_id=schools.id %} 如果您还有国家/地区变量。

    编辑:您的错误消息中的'('',)' 看起来并不像整数。你确定模板变量存在并且是整数吗?

    【讨论】:

    • 您好,感谢您的回复。这是有道理的,我已经复制并粘贴了你的建议。仍然在 /6/ Reverse 处出现错误 NoReverseMatch,用于 'schools' 关键字参数 '{'country_id': 6, 'schools_id': ''}' not found。尝试了 1 种模式:['(?P[0-9]+)/(?P[0-9]+)/$']
    • @SkyFall - 我已添加到我的答案中以解决您在参数方面遇到的问题。
    猜你喜欢
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 2013-03-09
    • 2013-04-22
    • 2017-01-04
    • 1970-01-01
    • 2022-06-29
    • 2020-09-17
    相关资源
    最近更新 更多