How can I fix this NoReverseMatch error? - python

Error Message:*<br/><br/>
NoReverseMatch at /
Reverse for 'get_travel_details' with arguments '()' and keyword arguments '{u'origin': u'bus_terminals.Bus_Terminal_Id', u'destination': u'bus_terminals.Bus_Terminal_Id', u'travel_date': u'travel_date'}' not found. 1 pattern(s) tried: ['(?P< travel_date >\\w+)/travel_date/(?P< origin >\\w+)/origin/(?P< destination >\\w+)/destination']
I am trying to pass values to the url's parameters through the form action, this is what my form tag looks in my html file:
<form method = "POST" action ="{% url 'brats:get_travel_details' travel_date='travel_date' origin='bus_terminals.Bus_Terminal_Id' destination='bus_terminals.Bus_Terminal_Id' %}" id = "find_travel_form">
And then my urls.py at the project folder:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^master/', admin.site.urls),
url(r'^', include('bus_reservation_system.urls')),
url(r'^(?P<travel_date>\w+)/travel_date/(?P<origin>\w+)/origin/(?P<destination>\w+)/destination$', include('bus_reservation_system.urls')),
]
And then my urls.py at the app folder:
from django.conf.urls import include, url
from . import views
app_name = "brats"
urlpatterns = [
url(r'^', views.index, name = "index"),
url(r'^(?P<travel_date>\w+)/travel_date/(?P<origin>\w+)/origin/(?P<destination>\w+)/destination', views.get_travel_details, name = "get_travel_details"),
]
The parameters: travel_date, origin, destination should be a string value to be passed.
And this is my views.py looks:
def get_travel_details(request, travel_date, origin, destination):
errors = []
if request.method == 'POST':
if not request.POST.get('travel_date', ''):
errors.append('Please determine your date of travel.\n')
if not request.POST.get('origin', ''):
errors.append('Please determine your point of origin.\n')
if not request.POST.get('destination', ''):
errors.append('Please determine your point of destination.\n')
if not errors:
all_bus = bus.objects.all()
elif errors:
travel_schedules = travel_schedule.objects.all()
bus_terminals = bus_terminal.objects.all()
bus_types = bus_type.objects.all()
data = {'travel_schedules': travel_schedules, 'bus_terminals': bus_terminals, 'errors': errors}
return render(request, 'pages/index.html', data)

Your url is still passing in strings, that include a ., which isn't included in your regex. I doubt that you actually want the dot and have a string id so just remove the quotes..
So change
{% url 'brats:get_travel_details' travel_date='travel_date' origin='bus_terminals.Bus_Terminal_Id' destination='bus_terminals.Bus_Terminal_Id' %}
to
{% url 'brats:get_travel_details' travel_date='travel_date' origin=bus_terminals.Bus_Terminal_Id destination=bus_terminals.Bus_Terminal_Id %}
And make sure that Bus_Terminal_Id's don't have any non-word characters

tl;dr
To fix the error, remove the following line from your main urls:
url(r'^(?P<travel_date>\w+)/travel_date/(?P<origin>\w+)/origin/(?P<destination>\w+)/destination$', include('bus_reservation_system.urls')),
Explanation
You have two urls pointing to the same app. So, everytime you write {% url 'brats:get_travel_details' ...}, Django resolves it to the last registered url which, in your case is this:
url(r'^(?P<travel_date>\w+)/travel_date/(?P<origin>\w+)/origin/(?P<destination>\w+)/destination$', include('bus_reservation_system.urls')),
Which finally gets resolved to this:
'(?P<travel_date>\w+)/travel_date/(?P<origin>\w+)/origin/(?P<destination>\w+)/destination/(?P<travel_date>\w+)/travel_date/(?P<origin>\w+)/origin/(?P<destination>\w+)/destination'
As you can see, the final resolved url requires 6 parameters but you're only passing it 3.
Which is why you're getting the error.

Related

Django 3.x - Custom Error Page is showing a 500 when it should be a 404

UPDATE: Added the code I was accessing that threw the error
For a CS50 project I'm working on with a wiki page, I'm trying to send the right custom 404 error when a user types a page that doesn't exist in wiki/TITLE however when I type a missing page, Django throws a 500 instead of a 404. Is this a common error or did I make my error message wrong? Debug is set to False and Allowed Hosts is configured to ['*'] in settings:
Here's my custom error handlers in views.py:
def error_404(request, exception):
context = {}
response = render(request, 'encyclopedia/error_404.html', context=context)
response.status_code = 404
return response
def error_500(request):
context = {}
response = render(request, 'encyclopedia/error_500.html', context=context)
response.status_code = 500
return response
Here's how they are in wiki/urls.py:
from django.contrib import admin
from django.urls import include, path
from django.conf.urls import handler404, handler500
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("encyclopedia.urls")),
]
handler404 = "encyclopedia.views.error_404"
handler500 = "encyclopedia.views.error_500"
here's the function in views.py that I'm accessing but going to wiki/C:
#function gets entry from index.html's <li>
def entry_page(request, entry):
name = entry # Places the title
print(f"checking the title: {entry}")
text = util.get_entry(entry) # Grabs the entry using the util function
html = md_converter(text)
if text is not None:
return render(request, "encyclopedia/entry.html", {
"title": name,
"entry": html
})
And here's my urls.py for good measure:
from django.urls import path
from . import views
app_name = "encyclopedia"
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:entry>", views.entry_page, name="entry"),
path("wiki/edit/<str:title>", views.edit, name="edit"),
path("search", views.search, name="search"),
path("random", views.random_page, name="random"),
path("create_entry",views.create_entry, name="create_entry")
]
Here's what the terminal shows (my styles.css is throwing a 404 for some reason but I haven't changed anything there...that's a separate issue):
There could be something wrong with your code. Django doc clearly says
The 404 view is also called if Django doesn’t find a match after checking every regular expression in the URLconf.
https://docs.djangoproject.com/en/3.2/ref/views/#error-views
Figured it out. Thanks ya'll.
There was an error in the function I was using to grab the page. I wasn't checking to see if the URL was valid when looking up a particular wiki entry.
Changing entry_page in views.py to this made it work!:
def entry_page(request, entry):
if entry in util.list_entries():
name = entry # Places the title
text = util.get_entry(entry) # Grabs the entry using the util function
html = md_converter(text)
return render(request, "encyclopedia/entry.html", {
"title": name,
"entry": html
})
else:
return render(request, "encyclopedia/error_404.html" )
Glad it wasn't Django messing up, just me lol

Django unable to render my template because it is unable to find my url. This only happens with url patterns from one of my apps

Django is unable to load my template because "NoReverseMatch at /books/outlines/20
"
This issue lies within a link in the template:
New Blank Outline
Here is my outlines/urls.py
from django.urls import path
from .views import Dashboard
from . import views as outline_views
urlpatterns = [
path('<int:pk>/', outlines_views.outline, name='url-outline')
path('blank/<int:storyPk>', outline_views.newBlankOutline, name='url-blankOutline'),
path('test/', outline_views.testView, name = 'test')
]
urlpatterns += staticfiles_urlpatterns()
Here is the testView:
def testView(request):
return render(request, 'outlines/test.html')
Here is the outline view:
def outline(request, pk):
context = {
'storyPk': pk
}
return render(request, 'outlines/outline.html', context)
The django error tells me:
NoReverseMatch at /books/outlines/20
Reverse for 'test' not found. 'test' is not a valid view function or pattern name.
The weird thing is, if I change the url name in the template to a url name from another app's urls.py file, it renders the template no problem. Any idea why it can't find the url?
New Blank Outline
how about try this

DJango - NoReverseMatch Error

That is the exception value:
Reverse for '' with arguments '()' and keyword arguments '{'id': 1}' not found. 0 pattern(s) tried: []
index.html
<p>Estudiante: {{student.stduent_name}}</p>
The link should go to a route like this "127.0.0.1:8000/polls/1/". The route works fine out of the link.
views.py
def student_detail(request, id):
student = get_object_or_404(Student, id=id)
return render(request, 'polls/student_detail.html', {'student': student})
urls.py
urlpatterns = [
url(r'^$', views.index),
url(r'^polls/(?P<id>[0-9]+)/', views.student_detail),
]
Images:
Error details
Route tree
The first argument to the url template tag is the "url name". You need to specify a name when you define the route, something like:
url(r'^polls/(?P<id>[0-9]+)/', views.student_detail, name='student-detail'),
and then update your template to use it like:
{% url 'student-detail' id=student.id %}
See the documentation on the url template and url names.
The template code in the exception is different to the template code you've pasted in your question. The exception indicates your template tag looks like:
{% url polls.views.student_detail id=student.id %}
Note the missing quotes which is consistent with the exception. Without the quotes django is attempting to resolve polls.views.student_detail as a variable instead of passing it as a string to the template tag. Since it can't resolve you're passing a blank string to your template tag.
You are invoking an url by name but there's no such named url in the urls.py file.
your urlpatterns should be:
urlpatterns = [
url(r'^$', views.index),
url(r'^polls/(?P<id>[0-9]+)/', views.student_detail, name='student_detail'),
]
And then in your template:
<p>Estudiante: {{student.stduent_name}}</p>
notice that you don't need to explicitly pass the parameter name, Django transforms each parameter separated by space in the respective parameter specified in the url regex pattern.

DJango URL Reverse Error: argument to reversed() must be a sequence

Here is my urls.py
from django.conf.urls import include, url
from django.contrib import admin
from common.views import HomeView, LoadingSchoolView, ProcessSchoolView
urlpatterns = [
url(r'^$', HomeView.as_view(), name='Index'),
url(r'^admin/', include(admin.site.urls)),
url(r'^member/', include('member.urls', namespace='member')),
url(r'^common/', include('common.urls', namespace='common')),
In my common/urls.py
from django.conf.urls import url
from .views import QuerySchoolView
urlpatterns = {
url(r'^querySchool/(?P<q>[a-z]*)$', QuerySchoolView.as_view(), name='querySchool'),
}
Now, when I do
{% url 'common:querySchool' %},
It gives me a TypeError
TypeError at /member/register/learner
argument to reversed() must be a sequence
Request Method: GET
Request URL: http://127.0.0.1:8000/member/register/learner
Django Version: 1.8.2
Exception Type: TypeError
Exception Value:
argument to reversed() must be a sequence
Exception Location: /Users/enzii/python_env/django18/lib/python3.4/site-packages/django/core/urlresolvers.py in _populate, line 285
Python Executable: /Users/enzii/python_env/django18/bin/python3
Python Version: 3.4.3
Here is My View
class QuerySchoolView(View):
def get(self, request, q=""):
universities = University.objects.filter(Q(name__contains=q) |
Q(pinyin__contains=q) |
Q(province__contains=q) |
Q(country__contains=q))[:4]
returnObj = [{'unvis-name': u.name, 'country': u.country, 'province': u.province} for u in universities]
return HttpResponse(returnObj)
What is wrong with my {% url %} ?
You don't have a URL called "index", you have one called "Index".
And in your common/urls, you are using {} instead of [] to wrap the patterns.
In future, please post each question separately.
Query-1 Solution:
You have Index defined as the reverse name for the HomePage view in the urls but you are using index as the reverse name for the url in your template.
Change index to Index and your code will work.
<a class="btn btn-default-ar" href="{% url 'common:Index' %}">
Index will default to application namespace i.e common so accessing the reversed url by common namespace.
You can even do the opposite that is changing the reverse name in your urls to index without any change in the template. It will work.
Query-2 Solution:
Urlpatterns defined in the urls.py file should be a list of patterns. As Gocht mentioned in the comment, try changing the urlpatterns defined in common app urls to a list [].
common/urls.py
from django.conf.urls import url
from .views import QuerySchoolView
urlpatterns = [
url(r'^querySchool/(?P<q>[a-z]*)$', QuerySchoolView.as_view(), name='querySchool'),
]

Reverse for 'send_referral_code' with arguments '()' and keyword arguments '{}' not found

I am working with django in one of my web application where i am also using userena.In userena profile template(profile_detail.html) i have added a anchor tag such as..
<a href = {% url 'send_referral_code'%}>Click here</a>
now here the send_referral_code is name value which is declared in urls.py,the urls.py is..
from django.conf.urls import patterns, url, include
from django.conf import settings
from mail import views
urlpatterns = patterns('',
url(r'^$', views.send_referral_code,name='send_referral_code'),
)
and views.py is...
from accounts.models import MyProfile
from django.core.mail import send_mail
def send_referral_code(request):
referral_code = MyProfile.objects.get(user = request.user)
send_mail('referral_code','This is Your Referral Code','you#email',['user#example.com'],fail_silently = False)
in mention, both views.py and urls.py resides another app namely 'mail'
and this is my main urls.py ..
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
import photo
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'auth.views.home', name='home'),
# url(r'^shutterstock/', include('shutterstock.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^accounts/', include('userena.urls')),
url(r'^user_upload/',include('myprofile.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^showphoto/',include('photo.urls')),
url(r'^mailing/',include('mail.urls')),
)
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}),
(r'^something/hard/to/guess/', include('paypal.standard.ipn.urls')), )
now i am getting an error namely Reverse for 'send_referral_code' with arguments '()' and keyword arguments '{}' not found while i am trying to execute my site and its indicating the line
<a href = {% url 'send_referral_code'%}>Click</a>
in my profile_detail.html file of my userena apps.Now how can i solve this or whats the actual problem?
The reason its not working is because your view code is returning an error. All view methods must return a HttpResponse object.
Any method in Python that doesn't have have a return statement, returns None; and since you don't have a return statement in your view method it is returning None which causes the view to not work.
Try this instead:
from django.shortcuts import redirect
def send_referral_code(request):
referral_code = MyProfile.objects.get(user = request.user)
send_mail('referral_code',
'This is Your Referral Code',
'you#email.com',
['user#example.com'],
fail_silently=False)
return redirect('/')
I have found the answer of my own,the problem is occuring because ,i have put the variable value as a first argument of the send_mail function parameter,that is,
send_mail('referral_code','This is Your Referral Code','you#email', ['user#example.com'],fail_silently = False)
i have just change it just like that...
send_mail('Referral Code','This is Your Referral Code','you#email',['user#example.com'],fail_silently = False)
now its working well,probabely the error Reverse for 'send_referral_code' with arguments '()' and keyword arguments '{}' not found is showing because i have put the varible instead of a Simple subject.Since i have put the varible in the place of the subject,thats why its contradicting.

Categories

Resources