NoReverseMatch Unless Url Is In Main Project Urls.py - django

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.

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>

Related

How to redirect to an absolute url path in django?

I am trying to reroute to the "listing" path from the the watchlist page using the 'url' attribute in Django templates. However, the problem is that Django ignores the parts of the URL it has already used in rerouting (i.e."/watchlist") and so looks for the url with path "/watchlist/listing_title" instead of just "/listing_title", which is what I want. Is there a way to work around this?
urls.py
path("", views.index, name="index"),
path("<str:listing_title>", views.listing, name="listing"),
path("watchlist", views.watchlist, name="watchlist"),
watchlist.html
<a href={% url 'listing' listing.title %}">
It will never access watchlist, since the <str:listing_title> will match for /watchlist. You should reorder the paths, and work with:
path('', views.index, name='index'),
path('watchlist', views.watchlist, name='watchlist'),
path('<str:listing_title>', views.listing, name='listing'),
Django will enumerate over all the URL patterns top-to-bottom, and "fire" the first view that has a matching URL pattern. If we thus put <str:listing_title> first, it will match watchlist with that <str:…> path part, and thus never trigger the listing.

How to fix django appendslash runtime error?

So basically I have a pdf.html that is called upon by my view.
My form in the pdf.html is as follows:
<form action="{% url "soapdf:submitemail" %}" method="post">
{% csrf_token %}
{{ emailform }}
<input type="submit" value="Submit">
</form>
The corresponding function on views.py looks like this:
def submitemail(request):
if(request.method=='POST'):
return HttpResponse(request.POST['text_email'])
else:
return HttpResponse("false")
and my urls.py looks as follows:
app_name = 'soapdf' # use this to namespace the application so that you can use the url tagging scheme
urlpatterns = [
path('',views.get_pdf,name='get_pdf'),
path('submitemail/',views.submitemail,name='submitemail')
]
However on clicking the submit button I get the following error. My redirect has the slash but still doesnt work.
RuntimeError at /submitemail
You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to localhost:8000/submitemail/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
Any Ideas on how to fix this runtimeerror
Add trailing slash in your main urls.py where you have included this get_pdf urls
I think it's like
urlpatterns =[
path('get_pdf',include('yourapp.urls')),
]
and it will be
urlpatterns =[
path('get_pdf/',include('yourapp.urls')),
]
If SEO is not important, you can serve both with and without slash. In Django 3.X:
from django.urls import re_path
urlpatterns = [
re_path('^/?$',views.get_pdf,name='get_pdf'),
re_path('^submitemail/?$',views.submitemail,name='submitemail')
]
But if SEO is important, it is better to add slash automatically by Nginx or something else.

Can't figure out why django variables aren't passed into template

I've been working on this for a few hours and for the life me of I can't get a variable from my django app into a template.
html:
{% block content %}
{{test}}
{% endblock content %}
views:
def home(request):
context = {'test' : "test"}
return render(request, "/dbus/templates/index.html", context)
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name = 'home')
]
(note: I left the imports out of the view code sample I provided)
I think you dont need to add 'templates' in the argument "/dbus/templates/index.html"
If dbus is your django-app and templates is a folder inside this django-app, then by convention, you've to add a subfolder named dbus inside this templates folder.
All HTML files regarding the django-app 'dbus' should be stored inside this subfolder named 'dbus' (which comes inside templates folder)
The path of index.html should looks like: YourProjectFolder/dbus/templates/dbus/index.html
If you're right till this part, then you've to render the html page like "dbus/index.html"
You dont need to add that templates directory in the render argument.
So correct line is: return render(request, "dbus/index.html", context)
This should solve your problem!
Turn's out the issues was due to caching in either Nginx or uWSGI. I restarted both and the changes started working

django 1.10 one app page with a link redirect to another app page

I'm new to django server and trying to build a simple website for user registration. Here is the problem, I create my own app with index.html as my homepage. I also used another user registration app from:
https://github.com/pennersr/django-allauth/tree/master/allauth
I was trying to add the app to my homepage with a 'sign up' link. Basically, the account part, and ideally, the link can direct to: http://127.0.0.1:8000/accounts/login/
However, when I run the server, it gives me error:
Reverse for 'base' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
server result:
Both apps work fine individually, but when I try to add the link to my homepage, the error occurs.
The related code in index.html file in my first app:
<li>Log In</li>
The full path for index.html in my project is:
project/app1/templates/app1/index.html
The full path for base.html in my project is:
project/allauth/templates/base.html
I know I probably need to add a url line in my first app's urls.py file, and a view to show it, but how can I do it? Can anyone help me with this, much appreciate.
<li>Log In</li>
this line uses URL reversing, 'allauth:base' is the URL patterns, allauth prefix is the namespace, base is the named URL. You must define the namespace and named URL in the urls.py first.
Define your namespace in project's urls.py file like this:
from django.conf.urls import include, url
urlpatterns = [
url(r'^author-polls/', include('polls.urls', namespace='author-polls')),
url(r'^publisher-polls/', include('polls.urls', namespace='publisher-polls')),
]
Define your named URL in app's urls.py file like this:
from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
...
]
all the help you need is in this document: Naming URL patterns

django templates url parse error

I am trying to construct a URL in the template as shown but it ends up getting the following error. What am I doing wrong here?
EDIT:
'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs.
urls.py
url(r'^launch$', views.LaunchInstanceView.as_view(), name='launch')
templates :
<a href="{%url launch %}" >Launch</a>
I've also tried
urls.py
url(r'^launch$', views.LaunchInstanceView.as_view(), name='instance.views.launch')
templates :
<a href="{%url instances.views.launch %}" >Launch</a>
Edit 1:
with quotes get the error as
<a href="{%url 'launch' %}" >Launch</a>
Reverse for 'launch' with arguments '()' and keyword arguments '{}' not found.
urls.py
urlpatterns = patterns(VIEW_MOD,
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^launch$', views.LaunchInstanceView.as_view(), name='launch'),
url(r'^(?P<instance_id>[^/]+)/$',
views.DetailView.as_view(), name='detail'),
)
views.py
class LaunchInstanceView(workflows.WorkflowView):
workflow_class = project_workflows.LaunchInstance
def get_initial(self):
initial = super(LaunchInstanceView, self).get_initial()
initial['project_id'] = self.request.user.tenant_id
initial['user_id'] = self.request.user.id
return initial
It should be:
<a href="{% url 'launch' %}" >Launch</a>
You should provide name as 'launch' is your url.
Please edit that if you want to call url like <a href="{%url 'launch' %}" >Launch</a>
url(r'^launch$', views.LaunchInstanceView.as_view(), name='launch')
if i am getting wrong. Please update your question so i can understand your problem easily.
If the above provied urls.py is you ROOT_URLCONF.. then following should work:
url(r'^launch/$', views.LaunchInstanceView.as_view(), name='launch') #Its a good practice to put '/' at the end of the pattern name, so if someone enters a '/' at the end in the browser it doesn't give 404
and
<a href="{% url 'launch' %}" >Launch</a>
Otherwise
Please check your settings.py file and See, to which file ROOT_URLCONF points to.
if it is different and you are including the above urls.py in the root urls.py file, then please check if it is either being included using a namespace e.g
url(r'^xyz/', include('path_to_above_urls.py', namespace='abc')),
or there's some other url with same name in root urls.py e.g:
url(r'some_pattern$', someview.as_view(), name='launch'),
url(r'^xyz/', include('path_to_above_urls.py')),
In 1st case you will have to access the url with {% url 'abc:launch' %}
In 2nd case you will have to change the name to make it unique.