Noreversematch django ошибка

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

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.

Django Exceptions¶

Django raises some of its own exceptions as well as standard Python exceptions.

Django Core Exceptions¶

Django core exception classes are defined in django.core.exceptions.

AppRegistryNotReady

exception AppRegistryNotReady[source]

This exception is raised when attempting to use models before the app
loading process
, which initializes the ORM, is
complete.

EmptyResultSet

exception EmptyResultSet[source]

EmptyResultSet may be raised during query generation if a query won’t
return any results. Most Django projects won’t encounter this exception,
but it might be useful for implementing custom lookups and expressions.

FieldDoesNotExist

exception FieldDoesNotExist[source]

The FieldDoesNotExist exception is raised by a model’s
_meta.get_field() method when the requested field does not exist on the
model or on the model’s parents.

SuspiciousOperation

exception SuspiciousOperation[source]

The SuspiciousOperation exception is raised when a user has
performed an operation that should be considered suspicious from a security
perspective, such as tampering with a session cookie. Subclasses of
SuspiciousOperation include:

  • DisallowedHost
  • DisallowedModelAdminLookup
  • DisallowedModelAdminToField
  • DisallowedRedirect
  • InvalidSessionKey
  • RequestDataTooBig
  • SuspiciousFileOperation
  • SuspiciousMultipartForm
  • SuspiciousSession
  • TooManyFieldsSent

If a SuspiciousOperation exception reaches the ASGI/WSGI handler level
it is logged at the Error level and results in
a HttpResponseBadRequest. See the logging
documentation
for more information.

PermissionDenied

exception PermissionDenied[source]

The PermissionDenied exception is raised when a user does not have
permission to perform the action requested.

ViewDoesNotExist

exception ViewDoesNotExist[source]

The ViewDoesNotExist exception is raised by
django.urls when a requested view does not exist.

MiddlewareNotUsed

exception MiddlewareNotUsed[source]

The MiddlewareNotUsed exception is raised when a middleware is not
used in the server configuration.

ImproperlyConfigured

exception ImproperlyConfigured[source]

The ImproperlyConfigured exception is raised when Django is
somehow improperly configured – for example, if a value in settings.py
is incorrect or unparseable.

FieldError

exception FieldError[source]

The FieldError exception is raised when there is a problem with a
model field. This can happen for several reasons:

  • A field in a model clashes with a field of the same name from an
    abstract base class
  • An infinite loop is caused by ordering
  • A keyword cannot be parsed from the filter parameters
  • A field cannot be determined from a keyword in the query
    parameters
  • A join is not permitted on the specified field
  • A field name is invalid
  • A query contains invalid order_by arguments

ValidationError

exception ValidationError[source]

The ValidationError exception is raised when data fails form or
model field validation. For more information about validation, see
Form and Field Validation,
Model Field Validation and the
Validator Reference.

NON_FIELD_ERRORS

NON_FIELD_ERRORS

ValidationErrors that don’t belong to a particular field in a form
or model are classified as NON_FIELD_ERRORS. This constant is used
as a key in dictionaries that otherwise map fields to their respective
list of errors.

BadRequest

exception BadRequest[source]

The BadRequest exception is raised when the request cannot be
processed due to a client error. If a BadRequest exception reaches the
ASGI/WSGI handler level it results in a
HttpResponseBadRequest.

RequestAborted

exception RequestAborted[source]

The RequestAborted exception is raised when an HTTP body being read
in by the handler is cut off midstream and the client connection closes,
or when the client does not send data and hits a timeout where the server
closes the connection.

It is internal to the HTTP handler modules and you are unlikely to see
it elsewhere. If you are modifying HTTP handling code, you should raise
this when you encounter an aborted request to make sure the socket is
closed cleanly.

SynchronousOnlyOperation

exception SynchronousOnlyOperation[source]

The SynchronousOnlyOperation exception is raised when code that
is only allowed in synchronous Python code is called from an asynchronous
context (a thread with a running asynchronous event loop). These parts of
Django are generally heavily reliant on thread-safety to function and don’t
work correctly under coroutines sharing the same thread.

If you are trying to call code that is synchronous-only from an
asynchronous thread, then create a synchronous thread and call it in that.
You can accomplish this is with asgiref.sync.sync_to_async().

URL Resolver exceptions¶

URL Resolver exceptions are defined in django.urls.

Resolver404

exception Resolver404

The Resolver404 exception is raised by
resolve() if the path passed to resolve() doesn’t
map to a view. It’s a subclass of django.http.Http404.

NoReverseMatch

exception NoReverseMatch

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

Database Exceptions¶

Database exceptions may be imported from django.db.

Django wraps the standard database exceptions so that your Django code has a
guaranteed common implementation of these classes.

exception Error[source]
exception InterfaceError[source]
exception DatabaseError[source]
exception DataError[source]
exception OperationalError[source]
exception IntegrityError[source]
exception InternalError[source]
exception ProgrammingError[source]
exception NotSupportedError[source]

The Django wrappers for database exceptions behave exactly the same as
the underlying database exceptions. See PEP 249, the Python Database API
Specification v2.0, for further information.

As per PEP 3134, a __cause__ attribute is set with the original
(underlying) database exception, allowing access to any additional
information provided.

exception models.ProtectedError

Raised to prevent deletion of referenced objects when using
django.db.models.PROTECT. models.ProtectedError is a subclass
of IntegrityError.

exception models.RestrictedError

Raised to prevent deletion of referenced objects when using
django.db.models.RESTRICT. models.RestrictedError is a subclass
of IntegrityError.

HTTP Exceptions¶

HTTP exceptions may be imported from django.http.

UnreadablePostError

exception UnreadablePostError

UnreadablePostError is raised when a user cancels an upload.

Sessions Exceptions¶

Sessions exceptions are defined in django.contrib.sessions.exceptions.

SessionInterrupted

exception SessionInterrupted[source]

SessionInterrupted is raised when a session is destroyed in a
concurrent request. It’s a subclass of
BadRequest.

Transaction Exceptions¶

Transaction exceptions are defined in django.db.transaction.

TransactionManagementError

exception TransactionManagementError[source]

TransactionManagementError is raised for any and all problems
related to database transactions.

Testing Framework Exceptions¶

Exceptions provided by the django.test package.

RedirectCycleError

exception client.RedirectCycleError

RedirectCycleError is raised when the test client detects a
loop or an overly long chain of redirects.

Python Exceptions¶

Django raises built-in Python exceptions when appropriate as well. See the
Python documentation for further information on the Built-in Exceptions.

Решил освоить 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. Я затеял это ради обучение и практики.
При этом я уже не первый раз пытаюсь сделать какие то тестовые проектики не по видео, а самостоятельно. И до этого момента такие конструкции работали.
Вообшем у меня прям тотальное не понимание почему срабатывает эта ошибка.

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.

With django-extensions you can make sure your route in the list of routes:

./manage.py show_urls | grep path_or_name

If the route is missing you probably have not imported the application.

The Django Bootstrap3 Example article tells you how to develop a user, department, and employee management website using Django and bootstrap3. The example website provides a user, department, and employee list page.

Now I want to add a link to the employee name on the employee list page. Then when the user clicks the employee name link, it will display the employee detail data on a new page.

1. How To Produce Django Url NoReverseMatch Error.

  1. In this example, the user Jerry’s detailed data URL link is http://127.0.0.1:8000/dept_emp/emp_detail/jerry/13919283928/.
  2. The above URL contains the below five parts.
  3. Website root path: http://127.0.0.1:8000/
  4. Django app context path : dept_emp/
  5. Employee detail page url : emp_detail/
  6. User name part : jerry/
  7. User mobile number part : 13919283928/
  8. Because one employee is identified uniquely by the combination of username and mobile number, so the employee detail page URL must contain username and mobile number.
  9. To achieve this I need to edit the employee detail page link URL in the employee list page ( DjangoHelloWorld / templates / dept_emp / emp_list.html ).
  10. Please note the <a href=”{% url ‘dept_emp:emp_detail’ user_name=emp.user.username mobile_number=emp.emp_mobile %}”>{{ emp.user.username }}</a> code below, the Django url tag has three parameters after it.
  11. ‘dept_emp:emp_detail’ : This is the Django-app-name : employee-detail-page-url.
  12. user_name=emp.user.username : The emp.user.username value (jerry) will be passed to the backend emp_detail view function’s user_name parameter.
  13. mobile_number=emp.emp_mobile : The emp.emp_mobile value (13919283928) will be passed to the backend emp_detail view function’s mobile_number parameter.
  14. Below is the full source code on the employee list page.
    {% for emp in emp_list %}
          
       <tr>
                          
          <td><input type="checkbox" id="emp_{{ emp.id }}" name="emp_{{ emp.id }}"></td>
         
          <td>{{ emp.id }}</td>
         
          <td>
               <a href="{% url 'dept_emp:emp_detail' user_name=emp.user.username mobile_number=emp.emp_mobile %}">{{ emp.user.username }}</a>
          </td>
          
          <td>{{ emp.get_dept_values }}</td>
          
          <td>{{ emp.emp_mobile }}</td>
                          
          <td>{{ emp.emp_salary }}</td>
                          
          <td>{{ emp.emp_onboard_date }}</td>
                        
       </tr>
                     
    {% endfor %}
  15. And I also need to add a URL mapping in DjangoHelloWorld / dept_emp / urls.py file like below.
    url(r'^emp_detail/(?P&lt;user_name&gt;s+)/(?P&lt;mobile_number&gt;d{10,18})/$', views.emp_detail, name='emp_detail'),
  16. From the URL mapping definition, we can see emp_detail URL should contain two parameters, one is passed to views.emp_detail function’s user_name, the other is passed to views.emp_detail function’s mobile_number parameter.
  17. But when I run the code, the page URL http://127.0.0.1:8000/dept_emp/emp_list/ returns the NoReverseMatch error like below.
    NoReverseMatch at /dept_emp/emp_list/
    Reverse for 'emp_detail' with keyword arguments '{'user_name': 'jerry', 'mobile_number': 13919283928}' not found. 1 pattern(s) tried: ['dept_emp/emp_detail/(?P<user_name>\s+)/(?P<mobile_number>\d{10,18})/$']
    

2. How To Fix Django Url NoReverseMatch Error.

  1. The above error confused me some time, but finally, I find it is a stupid error, it is as simple as the error message said. The URL match pattern is not correct. Below are the steps of how to fix it.
  2.  First, make your URL pattern as simple as possible. I change
    url(r'^emp_detail/(?P<user_name>s+)/(?P<mobile_number>d{10,18})/$', views.emp_detail, name='emp_detail'),

    to

    url(r'^emp_detail/(?P<user_name>.*)/(?P<mobile_number>.*)/$', views.emp_detail, name='emp_detail'),
  3. Then I find the URL matching rule takes effect, so this means the original user_name or mobile_number‘s regular expression pattern is not correct.
  4. Then I restore the mobile_number regular expression pattern as original like below, I find it works also.
    url(r'^emp_detail/(?P<user_name>.*)/(?P<mobile_number>d{10,18})/$', views.emp_detail, name='emp_detail'),
  5. Now, I am sure the user_name‘s regular expression pattern s+ is not what I want, after search google, I find s+ means any white space, and what I want is w+ ( any characters and digits ). Please refer to https://docs.python.org/3/howto/regex.html.
  6. Then I change the URL pattern to below and the URL mapping worked as expected.
    url(r'^emp_detail/(?P<user_name>w+)/(?P<mobile_number>d{10,18})/$', views.emp_detail, name='emp_detail'),

3. Conclusion.

  1. When you meet the NoReverseMatch error, just check your URL mapping pattern carefully.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Nonpdrm not found games cannot be installed or played как исправить
  • Nonexistent ошибка майнкрафт
  • Nonetype object is not iterable ошибка
  • Nonetype object is not callable ошибка
  • None of the available extractors could read the stream как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии