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

2.4k views Asked by At

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 %} ?

2

There are 2 answers

1
Daniel Roseman On BEST ANSWER

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.

4
Rahul Gupta On

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