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

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'),
]

Related

Page not found at /polls

I am a total beginner in "django" so I'm following some tutorials currently I' am watching https://youtu.be/JT80XhYJdBw Clever Programmer's tutorial which he follows django tutorial
Everything was cool until making a polls url
Code of views.py:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
HttpResponse("Hello World.You're at the polls index")
Code of polls\urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Code of Mypr\urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/',admin.site.urls),
path('polls/',include('polls.urls')),
]
I don't get it I did the same thing but I'm getting error not only polls.In one turtorial he decided to make blog,and again the same error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/
Using the URLconf defined in Mypr.urls, Django tried these URL patterns, in
this order:
admin/
The current path, polls/, didn't match any of these.
Please my seniors help me.
Note:I'm using the latest versions of django,windows and as editor I'm using Pycharm.
Already tried(and did not work):
from django.urls import path
from polls.views import index
urlpatterns = [
path('', index, name='index'),
]
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/
Using the URLconf defined in Mypr.urls, Django tried these URL patterns, in this order:
admin/
The current path, polls/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file.
Change that to False, and Django will display a standard 404 page.
try to access polls/ URL in your browser then you will access the page
Because you have accessed the URL of your project, you have to go to this URL to access your app
try by changing your code like this
from django.urls import path
from polls.views import index
urlpatterns = [
path('', index, name='index'),
]
I was facing the same error. Feel kinda dumb after figuring out how to solve this.
Your urls.py content is all right
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
But it must be included in the mysite\mysite\urls.py and not in mysite\urls.py.
That means the inner mysite/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it.

Django url variable catching

I'm having trouble at having Django urlpatterns catch a variable as an variable and instead take it as a set URL.
urlpatterns:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^about/', views.about),
url(r'^views/available_products/', views.available_products),
url(r'^views/productview/<int:product_id>/', views.productview)
]
When I host the server and go to /about/, /views/available_products/ or /admin/ they work fine, but trying to go to /views/productview/1/ gives a 404 error whereas going to /views/productview// gives a missing argument -error.
I tried to read the documentation and saw no obvious tell as to why my url variable argument wouldn't work, but clearly I'm doing something fundamentally wrong.
Here is an example error message from the debug page:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/views/productview/12/
Using the URLconf defined in firstdjango.urls, Django tried these URL patterns, in this order:
^admin/
^about/
^views/available_products/
^views/productview/<int:product_id>/
The current path, views/productview/12/, didn't match any of these.
And here is the same error message but where the URL I try with is the same as in urlpatterns:
TypeError at /views/productview/<int:product_id>/
productview() missing 1 required positional argument: 'product_id'
Request Method: GET
Request URL: http://localhost:8000/views/productview/%3Cint:product_id%3E/
Django Version: 1.11.8
Exception Type: TypeError
Exception Value:
productview() missing 1 required positional argument: 'product_id'
Server time: Sat, 10 Feb 2018 12:25:21 +0000
views.py:
from django.http import HttpResponse, Http404
from django.shortcuts import render
def starting_instructions(request):
return render(request, "webshop/instructions.html", {})
def about(request):
return HttpResponse("about page")
def productview(request, product_id):
"""
Write your view implementations for exercise 4 here.
Remove the current return line below.
"""
return HttpResponse("product {}".format(product_id))
def available_products(request):
"""
Write your view implementations for exercise 4 here.
Remove the current return line below.
"""
return HttpResponse("View not implemented!")
This url is not translated correctly.
see Request URL: http://localhost:8000/views/productview/%3Cint:product_id%3E/
You can use eighter path or re_path (which is similar to url and you can use regex in it so as you can use in url). So change your urlpatterns to.
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('about/', views.about),
path('views/available_products/', views.available_products),
path('views/productview/<int:product_id>/', views.productview)
]
EDIT
or if you really want to use url, use it like
url('^views/productview/(?P<product_id>\d+)/$', views.productview)
But using path is the Django 2.0+ approach. Also replacing url with re_path which is the same.

No Reverse Match when calling url from html file - Django

So I am trying to call my url by using the following in one of my html templates -
<a href="{% url 'socialx:index' %}">
My apps urls.py file looks like this -
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^socialx/', include('socialx.urls')),
url(r'^admin/', include(admin.site.urls)),
]
And the root urls.py file is like this -
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^socialx/', include('socialx.urls'), name='socialx'),
url(r'^admin/', include(admin.site.urls)),
]
When navigating to the app via browser I get the following error -
NoReverseMatch at /socialx/ 'socialx' is not a registered namespace
Have a look at the documentation
I think that when you include the url in urls.py you need to add a namespace
url(r'^socialx/', include('socialx.urls', namespace="socialx")),
And make sure that the url for going to the index page has a name=index.
See if that helps.

How can I fix this NoReverseMatch error?

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.

Django urlresolvers reverse for dynamically generated ids

I've got to test URLs that look like this:
http://127.0.0.1:8000/payment/pay/513623c9/
but I'm not sure how to say this to the reverse() function. This is my urls.py
from django.conf.urls import patterns, url
from payment import views
from payment.msn import *
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^msnstats/', MsnStats.finish_transaction, name='finish_transaction'),
url(r'^pay/(?P<payment_id>\w+)/$', views.pay, name='pay')
)
And this is what the relevant part of my views.py looks like:
def pay(request, payment_id):
try:
plan=PaymentPlan.objects.get(payment_id=payment_id)
The payment_id is generated for each plan, so I first create a plan, get its payment_id from the database, and somehow call it. I'm just not sure how to use reverse.
from django.core.urlresolvers import reverse
url = reverse('pay', args=[plan.payment_id])
or
url = reverse('pay', kwargs={'payment_id': plan.payment_id})
Both versions are valid.
UPDATE: If you include the payment.urls with namespace argument then you have to add this namespace to the url name in the reverse() call:
project/urls.py:
url(r'^payment/', include('payment.urls', namespace='payment')),
payment/tests.py:
response = self.client.get(reverse('payment:pay', args=[plan.payment_id]))

Categories

Resources