##この記事の内容
views.pyでこういうコードを打つと
def example(request):
return redirect('YYYY')
エラー
Reverse for 'YYYY' not found. 'YYYY' is not a valid view function or pattern name.
こんなエラーが出たときの対処法
##プロジェクトのurls.pyを確認
プロジェクトのurls.pyにおけるpathの第三引数で「namespace=」で名前を指定してあげないとredirectが該当のviewを探せません。
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('example.urls',namespace="example")),
]
##appのurls.pyを確認
「name=」で名前を指定してあげているか確認。
(以下の例では'YYYY')
from django.urls import path
from . import views
app_name = 'example'
urlpatterns = [
path('xxxx/',views.example,name='YYYY'),
]
##views.pyを確認
プロジェクトのurls.pyで指定したnamespaceも併せて以下のように指定すると、
redirectが該当のviewを探せます。
def example(request):
return redirect('example:YYYY')
]
##参照URL
https://docs.djangoproject.com/en/3.1/topics/http/urls/#naming-url-patterns
Naming URL patterns¶
In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. The string used for the URL name can contain any characters you like. You are not restricted to valid Python names.
When naming URL patterns, choose names that are unlikely to clash with other applications’ choice of names. If you call your URL pattern comment and another application does the same thing, the URL that reverse() finds depends on whichever pattern is last in your project’s urlpatterns list.
Putting a prefix on your URL names, perhaps derived from the application name (such as myapp-comment instead of comment), decreases the chance of collision.
You can deliberately choose the same URL name as another application if you want to override a view. For example, a common use case is to override the LoginView. Parts of Django and most third-party apps assume that this view has a URL pattern with the name login. If you have a custom login view and give its URL the name login, reverse() will find your custom view as long as it’s in urlpatterns after django.contrib.auth.urls is included (if that’s included at all).
You may also use the same name for multiple URL patterns if they differ in their arguments. In addition to the URL name, reverse() matches the number of arguments and the names of the keyword arguments. Path converters can also raise ValueError to indicate no match, see Registering custom path converters for details.
とか
URL namespaces and included URLconfs¶
Application namespaces of included URLconfs can be specified in two ways.
Firstly, you can set an app_name attribute in the included URLconf module, at the same level as the urlpatterns attribute. You have to pass the actual module, or a string reference to the module, to include(), not the list of urlpatterns itself.
このあたりの邦訳等、のちほど整理します