NoReverseMatch Unless Url Is In Main Project Urls.py

Brenden

I have a project called 'my_project' and within that project I have an app called 'my_app' so I have two urls.py files. All of my url's for my_app are located within it's urls.py file and work correctly, except one. That one is 'download_file'. My site works when this is included in my_project's urls.py, but when it's in my_app's urls.py I get a NoReverseMatch error on page load.

I don't know why this url only works when it's located in my main projects url's folder. I suspect it has something to do with the regex, though I can't figure it out.

The user would be on this page:

http://127.0.0.1:8000/user_area/username/classes

then click the 'download' link:

<a href="{% url 'download_file' file_path=item.instance.user_file %}" target='_blank'>{{ item.instance.filename }}</a>

my_project.py

urlpatterns = [
# reference to my_app
re_path(r'^user_area/(?P<username>[\w-]+)/', include('my_app.urls')),
]

# this works
url(r'^download_file/(?P<file_path>(.+)\/([^/]+))$', users_views.DownloadFile.as_view(), name='download_file'),
]

my_app.py

urlpatterns = [
path('classes', views.classes, name='classes'),

# if I remove the url from my_project.py this one returns NoReverseMatch on page load
url(r'^download_file/(?P<file_path>(.+)\/([^/]+))$', users_views.DownloadFile.as_view(), name='download_file'),

Thank you.

MattRowbum

The problem is occurring because your URL template tag is providing only one parameter: file_path.

This works when the URL is declared in your project urls.py, because only one parameter is needed.

When you try to use the URL in my_app.urls, you need to also provide the username parameter. You will need to use something like:

<a href="{% url 'download_file' username=request.user.username file_path=item.instance.user_file %}" target='_blank'>{{ item.instance.filename }}</a>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related