Noreversematch django ошибка

The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you’ve provided in any of your installed app’s urls.

The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.

To start debugging it, you need to start by disecting the error message given to you.

  • NoReverseMatch at /my_url/

    This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched

  • Reverse for ‘my_url_name’

    This is the name of the url that it cannot find

  • with arguments ‘()’ and

    These are the non-keyword arguments its providing to the url

  • keyword arguments ‘{}’ not found.

    These are the keyword arguments its providing to the url

  • n pattern(s) tried: []

    These are the patterns that it was able to find in your urls.py files that it tried to match against

Start by locating the code in your source relevant to the url that is currently being rendered — the url, the view, and any templates involved. In most cases, this will be the part of the code you’re currently developing.

Once you’ve done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you’ve recently changed.

Now that you’ve discovered where the error is occuring, use the other parts of the error message to work out the issue.

The url name

  • Are there any typos?
  • Have you provided the url you’re trying to access the given name?
  • If you have set app_name in the app’s urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').

Arguments and Keyword Arguments

The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.

Assuming the url you’re matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.

If they aren’t correct:

  • The value is missing or an empty string

    This generally means that the value you’re passing in doesn’t contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you’ll need to figure out why this value doesn’t get passed through correctly.

  • The keyword argument has a typo

    Correct this either in the url pattern, or in the url you’re constructing.

If they are correct:

  • Debug the regex

    You can use a website such as regexr to quickly test whether your pattern matches the url you think you’re creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.

    Common Mistakes:

    • Matching against the . wild card character or any other regex characters

      Remember to escape the specific characters with a \ prefix

    • Only matching against lower/upper case characters

      Try using either a-Z or \w instead of a-z or A-Z

  • Check that pattern you’re matching is included within the patterns tried

    If it isn’t here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)

Django Version

In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.


If you’re still unable to track down the problem, then feel free to ask a new question that includes what you’ve tried, what you’ve researched (You can link to this question), and then include the relevant code to the issue — the url that you’re matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.

The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you’ve provided in any of your installed app’s urls.

The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.

To start debugging it, you need to start by disecting the error message given to you.

  • NoReverseMatch at /my_url/

    This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched

  • Reverse for ‘my_url_name’

    This is the name of the url that it cannot find

  • with arguments ‘()’ and

    These are the non-keyword arguments its providing to the url

  • keyword arguments ‘{}’ not found.

    These are the keyword arguments its providing to the url

  • n pattern(s) tried: []

    These are the patterns that it was able to find in your urls.py files that it tried to match against

Start by locating the code in your source relevant to the url that is currently being rendered — the url, the view, and any templates involved. In most cases, this will be the part of the code you’re currently developing.

Once you’ve done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you’ve recently changed.

Now that you’ve discovered where the error is occuring, use the other parts of the error message to work out the issue.

The url name

  • Are there any typos?
  • Have you provided the url you’re trying to access the given name?
  • If you have set app_name in the app’s urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').

Arguments and Keyword Arguments

The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.

Assuming the url you’re matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.

If they aren’t correct:

  • The value is missing or an empty string

    This generally means that the value you’re passing in doesn’t contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you’ll need to figure out why this value doesn’t get passed through correctly.

  • The keyword argument has a typo

    Correct this either in the url pattern, or in the url you’re constructing.

If they are correct:

  • Debug the regex

    You can use a website such as regexr to quickly test whether your pattern matches the url you think you’re creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.

    Common Mistakes:

    • Matching against the . wild card character or any other regex characters

      Remember to escape the specific characters with a \ prefix

    • Only matching against lower/upper case characters

      Try using either a-Z or \w instead of a-z or A-Z

  • Check that pattern you’re matching is included within the patterns tried

    If it isn’t here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)

Django Version

In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.


If you’re still unable to track down the problem, then feel free to ask a new question that includes what you’ve tried, what you’ve researched (You can link to this question), and then include the relevant code to the issue — the url that you’re matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.

A NoReverseMatch error is a common Django error and one that can often be fixed with just one line of code.

NoReverseMatch at /
Reverse for 'index' not found. 'index' is not a valid view function or pattern name.

The cause of the error is likely to be in your template (a HTML file), in urls.py or views.py.

The NoReverseMatch error happens when Django can’t find a path in urls.py that matches the provided name.

URLs can be referenced by name in templates, or in a view using the reverse, reverse_lazy, or redirect functions.

Solving the error is a matter of making sure the correct name and the correct arguments are supplied.

What is a URL name?

In urls.py, URL patterns take the following format:

path("filter/<str:status>", views.filter_tasks, name="filter")

This URL has a name of filter. Whenever you need to make reference to a URL, you can use the name instead of having to write out the whole URL.

Django will take the name and look it up in urls.py. If it finds a match, it will return the URL of the match. If it cannot find a match, it will raise a NoReverseMatch error.

Common Causes

1. Typo in urls.py or your template

This particular error has the name of the URL that couldn’t be matched:

NoReverseMatch at /
Reverse for 'index' not found. 'index' is not a valid view function or pattern name.

Go to urls.py file and confirm that there is a URL named index:

# todo/urls.py
from django.urls import path
from todo import views

urlpatterns = [
    path("", views.index, name="index"),
]

2. You forgot to put quotations around the name

Consider this HTML snippet:

<a href="{% url filter Status.TODO 123%}">To Do</a>

This will give you the following error:

NoReverseMatch at /
Reverse for '' not found. '' is not a valid view function or pattern name.

You can fix this by putting single quotations around filter, the URL name.

<a href="{% url 'filter' Status.TODO 123%}">To Do</a>

3. You have provided too many or too few arguments

Consider this error:

NoReverseMatch at /
Reverse for 'filter' with arguments '(Task.StatusChoice.TODO, 123)' not found. 2 pattern(s) tried: ['filter/(?P<status>[^/]+)\\Z', 'filter/(?P<status>[^/]+)\\Z']

This is what I provided in my template:

<a href="{% url 'filter' Status.TODO 123%}">To Do</a>

And this is the URL pattern in urls.py:

path("filter/<str:status>", views.filter_tasks, name="filter")

Django has matched the name but my template provided 2 arguments; the URL path only expects one.

Because the number of arguments doesn’t match, Django cannot match the URL name, even though there is a URL pattern named “filter”.

The URL pattern in this example expects one argument. You can fix the error by removing the extra argument from the template.

4. Your app’s URLs haven’t been registered

Say you have checked your template and urls.py and there definitely isn’t a typo. The link in your template has the correct syntax and the correct number of arguments have been supplied.

The next step is to check the URLs for your app have been imported into the main urls.py.

Django projects are organised by apps. Your site directory (the folder that contains settings.py also has a file called urls.py that contains the index of URLs for the entire project. Each app can have its own urls.py file, but those URLs need to be imported into the main urls.py folder.

If you only have one app, then this won’t be the cause of your error. If you have one app and the URLs haven’t been imported into urls.py properly then you will get this screen instead of a NoReverseMatch error:

Check your site’s main urls.py file.

If you haven’t imported all the URLs for your app, then you will need to import include from django.urls and add a path to the URL patterns.

How to include your app’s URLs:

For example, my main urls.py file looks like this:

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

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("sample.urls")),
    path("", include("todo.urls")),
]

5. Error in “reverse”, “reverse_lazy” or “redirect”

NoReverseMatch errors don’t just happen in templates. They can happen anywhere in your code that tries to get a URL from a URL name. They are often used in views.py to redirect the user.

Three common functions that do this are:

  • Reverse
  • Reverse Lazy
  • Redirect

The error could be in the name of the URL or the arguments supplied.

Consider this URL pattern:

path("filter/<str:status>", views.filter_tasks, name="filter")

It has a name of “filter” and accepts one argument- a string called “status”.

Because the URL pattern has parameters, reverse("filter") will return a NoReverseMatch error.

Instead, you must provide the “status” argument:

url = reverse("filter", args=["complete"])

The following is also acceptable if you prefer to name your arguments:

url = reverse("filter", kwargs={"status": "complete"})

Conclusion

NoReverseMatch errors occur when you are trying to get the URL from its name.

This error often occurs in templates, when you are trying to add a link to another page, or in views.py when you want to redirect a request to another view.

In both cases, it can be as simple as checking the name against urls.py. If the name matches, then check if the correct number of arguments have been supplied. Providing too many or too few arguments will trigger the error.

If that still hasn’t fixed the issue, then check that the URLs of you app have been included in your site’s main urls.py (the one in the same folder as settings.py). If the urls.py belonging to an app hasn’t been included, then Django won’t be able to find it.

Understand More

If you are new to Django, then you may find some examples helpful.

This article from my To Do list tutorial goes through setting up URLs for the first time.

This article from the same tutorial series, gives an example of how to implement URLs with multiple arguments.

Sometimes you may encounter NoReverseMatch Error while using Django-based websites & applications. This is because Django is unable to find URL that matches the url_name specified in your website templates. In this article, we will look at the various causes for this error and how to fix them.

When you mention a URL in template within {% url … %} tag then Django tries to find that URL in urls.py whose url_name parameter matches the value you have mentioned in your template. When is it unable to find a URL that matches your specified url_name, it returns NoReverseMatch Error. Basically, you get this error when Django is unable to find a Reverse Match for the URL name you have mentioned in your template.

How to Fix NoReverseMatch Error in Django

Let us say you have the following configuration in urls.py.

from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
    #...
    path('articles/<int:year>/', views.year_archive, name='news-year-archive'),
    #...
]

Here are some common reasons for NoReverseMatch Error in Django.

1. Using wrong URL name in template

The most common reason why you get this error is because you are using wrong URL name. For example, in the anchor tag below, url name is news-year-archives instead of news-year-archive as defined in urls.py above.

<a href="{% url 'news-year-archive' 2021 %}">2021 Archive</a>

2. Incorrect Commented HTML code

Please note, that Django parses the template tags and qualifiers inside commented HTML code also. For example, even if you comment the above mentioned anchor tag, you will still get the error.

<!--<a href="{% url 'news-year-archive' 2021 %}">2021 Archive</a>-->

So please check your commented HTML code as well to make sure that it is correct.

3. Incorrect Arguments & Keywords

Make sure that you pass the correct number of URL arguments in your template, as you have defined it in urls.py. For example, our URL defined above requires 1 argument. If you do not pass any argument you will get an error. Here is an example of URL that will give error.

<a href="{% url 'news-year-archive' %}">2021 Archive</a>

Please note, according to Django, a URL is a combination of URL string and arguments. So you need to pass the right number of arguments/keywords in your template to match URLs in urls.py file correctly.

4. Not including an app’s urls.py in your project

If you have a Django app test and if you do not include its URLs in your project’s urls.py then Django will not be able to find its URLs when you refer to them in your template. Here is an example of an incorrect configuration without your app’s urls.py included.

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

urlpatterns = [
    path('admin/', admin.site.urls),
]

Here is the correct configuration.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('test/', include('test.urls', namespace="test")),
]

5. Incorrect Regular Expressions in URL definition

The URL arguments are defined with the help of regular expressions in Django. If you have defined a URL to accept numerical argument in urls.py file and you pass an alphanumeric argument in your template then it will give a NoReverseMatch error. Here is an example of URL that accepts only numeric product IDs as its arguments.

re_path(r'product/(?:product-(?P<product_number>\d+)/)?$', product)

The following URL reference will give an error.

<a href="{% url 'product' abc %}">Product ABC</a>

6. Namespace Mismatch

If two or more of your applications use the same URL name, you can differentiate them with the help of namespaces. Once you have added a namespace for URL, you can call it using namespace:url_name syntax. Here is an example to call news-year-archive in test namespace.

<a href="{% url 'test:news-year-archive' 2012 %}">2012 Archive</a>

If you use wrong namespace for your URL in your template, then you may get NoReverseMatch error. This is because two URLs with same name and different namespaces can have different number of arguments/keywords.

In this article, we have looked at the various reasons as to why you may get NoReverseMatch Error in Django and how to fix them in each case.

Also read :

How to Convert PDF to Image/JPG in Ubuntu
How to Redirect with Query String in Apache
How to Check if Cookie is Set in Apache
How to Redirect Apache based on Cookie
How to Redirect Based on Hostname in Apache

Related posts:

Решил освоить django подумал что хватит повторять все за мужиком из видео надо что то самому попробывать без подсказок и столкнулся с этим.

Reverse for ‘boss’ with no arguments not found. 1 pattern(s) tried: [‘mymeteo/gorod/(?P[0-9]+)/$’]
Request Method: GET
Request URL: 127.0.0.1:8000/mymeteo/gorod/4
Django Version: 3.0.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for ‘boss’ with no arguments not found. 1 pattern(s) tried: [‘mymeteo/gorod/(?P[0-9]+)/$’]
Exception Location: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677
Python Executable: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3
Python Version: 3.8.1
Python Path:
[‘/Users/stepan/Desktop/django-pyowm/meteo’,
‘/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip’,
‘/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8’,
‘/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload’,
‘/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages’]
Server time: Вт, 10 Мар 2020 07:30:43 +0000

я понимаю что это за ошибка но не понимаю почему она выскакиваем у меня

вот так выглядит urls.py

from django.urls import path, include
from . import views

urlpatterns = [
    path ('list/', views.ListGorod.as_view(), name = 'listgorod'),
    path ('gorod/<int:id>/', views.MeteoList.as_view(), name = 'boss'),
]

вот так выглядит views.py

class MeteoList(View):

	def get (self, request, id):
		obj = Gorod.objects.get ( id__iexact = id)

		form = GorodForm(instance=obj)

		try:

			o=pyowm.OWM("262fea7ee569218476043b47466017ea")
			obs=o.weather_at_place(obj.gorod)
			w=obs.get_weather()
		except:
			o=pyowm.OWM("262fea7ee569218476043b47466017ea")
			obs=o.weather_at_place('biysk, RUS')
			w=obs.get_weather()

		wind = w.get_wind()
		temperature = w.get_temperature('celsius')
		return render(request, 'mymeteo/meteo_list.html',  context ={'temp' : w, 'temperature' : temperature, 'form':form})

	def post (self, request, id):
		obj = Gorod.objects.get (id__iexact = id)
		b_form = GorodForm(request.POST, instance=obj)

		new_obg = b_form.save()



		try:

			o=pyowm.OWM("262fea7ee569218476043b47466017ea")
			obs=o.weather_at_place(obj.gorod)
			w=obs.get_weather()
		except:
			o=pyowm.OWM("262fea7ee569218476043b47466017ea")
			obs=o.weather_at_place('biysk, RUS')
			w=obs.get_weather()

			wind = w.get_wind()
			temperature = w.get_temperature('celsius')
			return render(request, 'mymeteo/meteo_list.html',  context ={'temp' : w, 'temperature' : temperature, 'form':form})
		return redirect(new_obg)

и вот так выглядит get_absolute_url в моделях

class Gorod (models.Model):
	gorod = models.CharField(max_length = 50)

	def get_absolute_url(self):
		return reverse("boss", kwargs={"id" : self.id})

	


	def  __str__ (self):
		return self.gorod

я понимаю что скорей всего здесь помимо, есть еще куча других ошибок..но я даже до них добратся не могу.. потому что сталкиваюсь с NoReverseMatch. Я затеял это ради обучение и практики.
При этом я уже не первый раз пытаюсь сделать какие то тестовые проектики не по видео, а самостоятельно. И до этого момента такие конструкции работали.
Вообшем у меня прям тотальное не понимание почему срабатывает эта ошибка.

Понравилась статья? Поделить с друзьями:
  • Novar 1005 ошибки
  • Nova florida vela compact ошибки
  • Notreadableerror could not start video source ошибка
  • Noproviders ошибка вк ubuntu
  • Noto sans symbols powerpoint ошибка