Django urlresolvers: Need more than 2 values to unpack - django

I'm trying to upgrade from Django 1.3 to Django 1.4. I'm stuck with this error:
Python Version: 2.7.3
Django Version: 1.4.10
Exception Type: ValueError
Exception Value: need more than 2 values to unpack
The line that triggers that error is (In template /var/www/proj/src_1.4/templates/fragments/header.html, error at line 20):
<a id="login" href="{% url login %}" rel="nofollow">{% trans "Login" %}</a>
It works fine in Django 1.3.
I've tried the following:
python manage.py shell
>> from django.conf.urls import *
>> from django.core.urlresolvers import reverse
>> reverse('login')
Then this error appears:
ValueError Traceback (most recent call last)
/var/www/proj/env_1.4/local/lib/python2.7/site-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 reverse('login')
/var/www/proj/env_1.4/local/lib/python2.7/site-packages/django/core/urlresolvers.pyc in reverse(viewname, urlconf, args, kwargs, prefix, current_app)
474 resolver = get_ns_resolver(ns_pattern, resolver)
475
--> 476 return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
477
478 reverse_lazy = lazy(reverse, str)
/var/www/proj/env_1.4/local/lib/python2.7/site-packages/django/core/urlresolvers.pyc in _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs)
363 possibilities = self.reverse_dict.getlist(lookup_view)
364 prefix_norm, prefix_args = normalize(_prefix)[0]
--> 365 for possibility, pattern, defaults in possibilities:
366 for result, params in possibility:
367 if args:
ValueError: need more than 2 values to unpack
If I look at the info showed by Django when I try to load my project, "Local vars" shows that info:
self <RegexURLResolver urls (None:None) ^/>
args ()
_prefix u'/'
possibilities [([(u'accounts/login/', [])], 'accounts/login/$')]
lookup_view u'login'
prefix_norm u'/'
prefix_args []
kwargs {}
Code in proj/urls.py
from django.conf.urls import *
urlpatterns += patterns('',
url(r'^', include('home.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts', include('accounts.urls')),
Code in apps/accounts/urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^/register$',
'accounts.views.register',
name='register'),
url(r'^/login/$',
'django.contrib.auth.views.login',
{'template_name': 'accounts/login.html', 'authentication_form': AuthenticationForm},
name='login'),
I'll appreciate any help about that. Thanks.
Finally I found the error. It was an old app used for internationalization of URLs (i18nurls). Django 1.3 uses an external app, in Django > 1.4 internationalization was included in the core (Django: Internationalization: in URL patterns).
Thanks.

Not sure if this will fix your errors, but try to do the following:
In your main url.py replace
url(r'^accounts', include('accounts.urls')),
with
url(r'^accounts/', include('accounts.urls')), ### add the slash /
It is better to include the slash / in the outer urlpatterns rather then in the inner one.
Then, in the urls.py inside accounts replace
url(r'^/register$',...
url(r'^/login/$',....
with
url(r'^register/$',... ### delete dhe leading slashed, because you added it in `accounts/`
url(r'^login/$',.... ### finish both regex with the slash
Another suggestion would be to add a namespace:
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
Now refer inside to your template with "{% url 'accounts:login' %}"
In this way you will know better which url comes from which app. Check if these tips fixed your bug and if no, let me know

If this is your full urls.py code
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^/register$',
'accounts.views.register',
name='register'),
url(r'^/login/$',
'django.contrib.auth.views.login',
{'template_name': 'accounts/login.html', 'authentication_form': AuthenticationForm},
name='login'),
check you have not added the closing bracket )
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^/register$',
'accounts.views.register',
name='register'),
url(r'^/login/$',
'django.contrib.auth.views.login',
{'template_name': 'accounts/login.html', 'authentication_form': AuthenticationForm},
name='login'),
)

Related

Using the URLconf defined in tango_with_django_project.urls, Django tried these URL patterns, in this order:

I've been going through the Tango With Django 1.7 guide and I've come up with the following issue that I'm having troubles fixing:
Using the URLconf defined in tango_with_django_project.urls, Django
tried these URL patterns, in this order:
1. ^$ [name='index']
2. ^about/$ [name='about']
3. ^category/(?P<category_name_slug>[\w\-]+)/$ [name='category']
4. ^admin/
5. ^rango/$
6. ^about/
7. ^category/
8. ^media/(?P<path>.*)
The current URL, rango/category/python, didn't match any of these.
This is my rango/urls.py file
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns(' ',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$',
views.category, name='category')
)
In tango_with_django_project/urls.py I have
from django.conf.urls import patterns, include, url
from django.contrib import admin
from rango import views
from django.conf import settings
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^admin/', include(admin.site.urls)),
url(r'^rango/$', include('rango.urls')),
url(r'^about/', include('rango.urls')),
)
if settings.DEBUG:
urlpatterns+= patterns(
'django.views.static',
(r'^media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}),
)
In rango/views.py I have:
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from rango.models import Category
from rango.models import Page
def index(request):
category_list = Category.objects.order_by('-likes')[:5]
context_dict = {'categories': category_list}
return render(request, 'rango/index.html', context_dict)
def about(request):
return HttpResponse("Rango says: Hello world! <br/> <a
href='/rango/about'>About</a>")
def category(request, category_name_slug):
context_dict = {}
try:
category = Category.objects.get(slug=category_name_slug)
context_dict['category_name'] = category.name
pages = Page.objects.filter(category=category)
context_dict['pages'] = pages
context_dict['category'] = category
except Category.DoesNotExist:
return render(request, 'rango/category.html', context_dict)
I've been following the guide so I'm not quite sure what the problem is; I had a similar problem earlier on in the guide when I was getting the same error but with /about (never got this fixed).
Any idea what might be causing this problem? Any help is appreciated!
As already commented, the problem here is the definition of the URLconf, more precisely the inclusion of another URLconf that shall define every url that starts with rango/.... The crucial line is this one:
url(r'^rango/$', include('rango.urls')),
which should read instead
url(r'^rango/', include('rango.urls')),
The regex '^rango/$' captures: <start-of-string>rango/<end-of-string>
The regex '^rango/' captures: <start-of-string>rango/<whatever follows>, and that's where your included urls kick in.

Django doesn't load second page

I have just started Django, and I'm facing some difficulty.
When the first time I'm loading "localhost:8000/first_app" it is successfully loading index(), but on clicking on "About" link, url is changing to "localhost:8000/first_app/about/", but it is still loading "index()" and not "about()". Don't know what I'm missing.
Here's my project's URL:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^first_app/', include('first_app.urls')),
)
App's URL:
from django.conf.urls import patterns, url
from first_app import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/', views.index, name='about'),
)
And views.py:
from django.http import HttpResponse
def index(request):
return HttpResponse("Rango says: Hello world! <br/> <a href='/first_app/about'>About</a>")
def about(request):
return HttpResponse("This is the ABOUT page! <br /> <a href='/first_app/'>Index</a>")
I'm using Django 1.7 and python 2.7.
Thanks.
You need to define your URLs like this;
urlpatterns = patterns('',
url(r'^about/$', views.about, name='about'),
url(r'^/$', views.index, name='index'),
)
Basically '^$' is the beginning & end of the match. The ^ is the start of the pattern & the $ is the end of the pattern so keep that in mind when defining your URLs. It's good practice to use $ to end your urls to avoid views being rendered regardless of what you add to the URL after what you match in your pattern.

Error while integration a html template and url in django

I am using Django version 1.10.
Below is my urls.py(frontend),
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
url(r'^webApp/', include('webApp.urls')),
url(r'^admin/', admin.site.urls),
url(r'^home/$', 'frontend.views.home', name='home'),
]
Below is my urls.py(webApp),
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
And below is my views.py,
def home(request):
return render_to_response('home.html')
Here, frontend is my project name and webApp is my app name. And i have a home.html in my templates folder in frontend.
When I run,
python manage.py runserver 0.0.0.0:8000
I get the following error,
File "/root/frontend/frontend/urls.py", line 22, in <module>
url(r'^home/$', 'frontend.views.home', name='home'),
File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py", line 85, in url
raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include()
I don't know what I am doing wrong... Any guidance in the same?
In the urlpatterns list you are not properly using the function url (you're passing a string as its second argument, but it - in this case - [..] must be a callable [..]).
So... just change 'frontend.views.home' to frontend.views.home (i.e. remove single quotes) and you should be fine.

Create 404 with Django 1.4

I would like to show an 404 error if there's no proper entry in project_name/urls.py.
I read Writing your first Django app but i don't understood how to create a general error - not only for an app.
So i tried this:
TEMPLATE_DIRS = /var/www/first/templates
echo "404 ERROR" > /var/www/first/templates/404.html
in /var/www/first/urls.py:
from django.http import Http404
try:
...
url(r'^admin/', include(admin.site.urls)),
...
except:
raise Http404
After all i still get a 500 error if i call an unknown url.
Django uses the urls.py file to evaluate all the url patterns by order. If you want it to go to a certain page after it evaluated all the regex patterns and found no match, just add something like this as the last item in the urlpatterns tuple:
url('', views.defaultview),
with defaultview possibly being that 404 page.
django.views.defaults.page_not_found is a built-in django view that renders whatever's in templates/404.html.
It works with following in /var/www/first/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
...,
url(r'^admin/', include(admin.site.urls)),
...,
)

Why does Django throw a warning when loading my URLconf?

I have a Django app running on a production server. It is handled with gunicorn 0.14.2 behind nginx. When I reload the app (by reloading the gunicorn workers), I get this error:
Traceback (most recent call last):
File "/opt/nybooks/venv/myapp/lib/python2.6/site-packages/django/core/handlers/base.py", line 101, in get_response
request.path_info)
File "/opt/nybooks/venv/myapp/lib/python2.6/site-packages/django/core/urlresolvers.py", line 250, in resolve
for pattern in self.url_patterns:
File "/opt/nybooks/venv/myapp/lib/python2.6/site-packages/django/core/urlresolvers.py", line 283, in _get_url_patterns
raise ImproperlyConfigured("The included urlconf %s doesn't have any patterns in it" % self.urlconf_name)
ImproperlyConfigured: The included urlconf myapp.urls doesn't have any patterns in it
Others with this problem have commonly noted that it occurs while using reverse in a URLconf, but I am not using reverse in any URLconfs (nor are they used in any third-party apps). Also, this error only occurs in production -- never in development (using the Django dev server) or on my staging server (using gunicorn 0.14.2 behind nginx). It also doesn't seem to cause trouble with the site at any other time then during reloads.
Any ideas what's causing the problem?
Here's the main URLconf (and the one referenced in the stack trace):
from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
from django.http import HttpResponse, Http404
from django.views.generic.simple import direct_to_template, redirect_to
from myapp.apps.magazine.views import *
from myapp.apps.books.views import *
from myapp.apps.forms.views import *
from myapp.apps.blogext.views import *
from myapp.apps.sharing.views import expand_url, email_link_send
from myapp.apps.magazine.feeds import *
from satchmo_utils import urlhelper
from satchmo_store.urls import urlpatterns
from myapp.apps.myapp_shop.views import *
admin.autodiscover()
if settings.SHOP_BASE == '':
shopregex = '^'
else:
shopregex = '^' + settings.SHOP_BASE[1:] + '/'
myapp_patterns = patterns('',
# calendar
(r'^calendar/', include('events.urls')),
# for multimedia SWF access
#(r'^crossdomain.xml$', direct_to_template, {'template': 'crossdomain.xml'}),
# intercept checkout
# TODO: need to use a config value
(r'^catalog/checkout/$', 'myapp.apps.cart.views.myapp_checkout', {'SSL': not settings.LOCAL_DEV}, 'myapp_checkout'),
(r'^catalog/add/$', 'myapp.apps.cart.views.smart_add_wrapper', {}, 'myapp_smart_add'),
# URLs for NYRB apps
(r'^$', direct_to_template, {'template': 'newhomepage.html'}),
(r'^newhomepage/$', direct_to_template, {'template': 'newhomepage.html'}),
(r'^mobile/$', redirect_to, {'url': '/', 'permanent': True}),
(r'^books/authors/', include('myapp.apps.books.urls.authors')),
(r'^books/', include('myapp.apps.books.urls.books')),
(r'^articles/', include('myapp.apps.magazine.urls.articles')),
(
r'^mobile/articles/archives/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',
redirect_to,
{'url': '/articles/archives/%(year)s/%(month)s/%(day)s/%(slug)s/', 'permanent': True},
),
# for national poetry month (april)
url(
regex = r'^national-poetry-month/',
view = poetry_month,
name = 'poetry_month',
),
(r'^issues/', include('myapp.apps.magazine.urls.issues')),
(r'^contributors/', include('myapp.apps.magazine.urls.contributors')),
(r'^galleries/', include('myapp.apps.magazine.urls.illustrations')),
(r'^multimedia/', include('myapp.apps.multimedia.urls.multimedia')),
(r'^online/$', direct_to_template, {'template': 'online.html'}),
#(r'^search/', include('myapp.apps.search.urls')),
(r'^search/', include('solango.urls')),
(r'^textareas/', include('myapp.apps.textareas.urls')),
(r'', include('myapp.apps.forms.urls')),
(r'^utils/', include('myapp.apps.utils.urls')),
#(r'^rss/$', 'myapp.apps.magazine.views.rss_list'),
(r'^rss/huffpo/$', redirect_to, {'url': '/articles/feeds/huffpo/', 'permanent': False}),
(r'^rss/googlenews/$', redirect_to, {'url': '/articles/feeds/googlenews/', 'permanent': False}),
(r'^newsletter/', include('myapp.apps.newsletter.urls')),
(r'^subscriptions/', include('myapp.apps.newsubscriptions.urls')),
(r'^shared/', include('myapp.apps.sharing.urls')),
(r'^counter/', include('myapp.apps.counter.urls')),
# Redirects for legacy NYRB system
(r'^nyrev/(\w+)', uber_legacy_article_redirect),
(r'^nyrev/', redirect_to, {'url': '/'}),
(r'contents/(?P<legacy_date>\d+)/', legacy_issue_detail_redirect),
(r'^archives/browse/?$', legacy_browse_archives),
(r'^gallery/gallery-browse/?$', legacy_gallery_browse),
(r'^gallery/', legacy_illustration),
(r'authors/(?P<legacy_author_id>\d+)/', legacy_author_detail_redirect),
#(r'shop/product', legacy_book_detail_redirect),
(r'^shop/product/?$', legacy_product),
(r'^myapp/browse/?$', legacy_book_browse),
(r'blogs/myapplog/post/(\d+)/(?P<slug>[-\w]+)/$', solango_blogsearch_redirect),
# URL shortening
(r'^u/(?P<short_url>[a-zA-Z0-9]+)/$', expand_url),
# NYRB shop
(r'^shop/', include('myapp.apps.myapp_shop.urls')),
(r'^admin/shop/order/csv/?', csv_order_export_day),
(r'^admin/shop/order/(?P<order_id>\d+)/csv/?', csv_order_export),
# URLs for Savoy apps
(r'^tags/', include('savoy.contrib.sections.tag_urls')),
(r'^podcasts/', include('savoy.contrib.podcasts.urls')),
(r'^blogs/$', redirect_to, {'url': "/blogs/myapplog/", 'permanent': False}),
(r'^blogs/', include('savoy.contrib.blogs.urls')),
(r'^media/', include('savoy.core.media.urls')),
# this is to use our own edit profile view
(r'^users/(?P<username>.+)/edit/$', edit_profile),
(r'^users/', include('savoy.core.profiles.urls')),
# django-authopenid
(r'^account/getusername/', get_lost_username),
#(r'account/signin/?', 'myapp.apps.forms.views.dual_login'),
(r'account/signin/?', 'django.contrib.auth.views.login', {'template_name': 'authopenid/signin.html'}),
(r'account/signout/?', 'django.contrib.auth.views.logout', {'next_page': '/'}),
(r'account/sendpw/?', 'myapp.apps.forms.views.dual_sendpw'),
(r'account/resetpw/?', 'myapp.apps.forms.views.reset_pw'),
(r'account/signup/?', 'myapp.apps.forms.views.link_and_signup'),
#(r'^account/', include('django_authopenid.urls')),
# django-mailfriend
(r'^mail_friend/send/?', email_link_send),
(r'^mail_friend/', include('mailfriend.urls')),
# django.contrib.comments
# Django admin (Satchmo additions):
(r'^admin/print/(?P<doc>[-\w]+)/(?P<id>\d+)', 'shipping.views.displayDoc'),
(r'^admin/product/configurableproduct/(?P<id>\d+)/getoptions/', 'product.views.get_configurable_product_options'),
# Orders
(r'^admin/open-orders/$', 'myapp.apps.myapp_shop.views.open_orders'),
# Institutional subscription CSV
(r'^admin/subscriptions/institutionalsubscription\.csv', 'myapp.apps.subscriptions.views.institutional_sub_csv'),
# COUNTER admin for institutional reports
#(r'^admin/institution-counts/multiple-report/csv/$', 'myapp.apps.subscriptions.views.institution_multiple_csv'),
#(r'^admin/institution-counts/multiple-report/$', 'myapp.apps.subscriptions.views.institution_multiple_report'),
(r'^admin/institution-counts/institutions/(?P<id>\d+)/csv/', redirect_to, {'url': '/counter/%(id)s.csv'}),
(r'^admin/institution-counts/institutions/(?P<id>\d+)/$', redirect_to, {'url': '/counter/%(id)s/'}),
#(r'^admin/institution-counts/process_file/?$', 'myapp.apps.subscriptions.views.institution_process_file'),
(r'^admin/institution-counts/$', redirect_to, {'url': '/counter/'}),
# Django admin (standard)
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
# custom feeds
(r'^feed/author/(?P<slug>[-\w]+)/$', AuthorFeed()),
)
# attach satchmo patterns after our patterns so we can override if needed
from satchmo_store.urls import urlpatterns
urlpatterns = myapp_patterns + urlpatterns
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}),
)
My guess is it has to do with your satchmo patterns and overloading on the name "urlpatterns" which django specifically looks for.
Try
from satchmo_store.urls import urlpatterns as satchmo_patterns
urlpatterns = myapp_patterns + satchmo_patterns
#etc.
The strange behavior may be bacause before if settings.DEBUG, urlpatterns is empty for some reason.
When running the dev server, it gets populated with the urlpatterns from the static app. When running in production, it remains empty.
You can check this easily with a clause like
if urlpatterns:
# something is in urlpatterns
# What's its type, contents, ...?
else:
# urlpatterns is empty
Once you figured this out, you can dig deeper. You can also add the check in a unit test or do it directly in the python shell, by importing the urls module if you want to make it more robust.
I think, and this is just a hunch, your urls maybe fine, (since no issues arise in your staged dev machine, only reloading on prod) the problem maybe with the way gunicorn re-loads the modules, and the way python compiled code behaves between different versions of the interpreter and how iterators behave, but again this are all hunches.
I recommend that you use the same version of python that you have on production in your staged machine and see if you can recreate the error if there already same version, then it must be something else, the reason I ask is that most production machines tend to use older versions of python, though I could be wrong.
good luck.
Instead of the urlpatterns = myapp_patterns + urlpatterns stuff, surely we could instead call myapp_patterns urlpatterns off the bat, and have inside the end of it, something along the lines of:
(r'^', include('satchmo_store.urls')),
As this is the "Django" way to include URL patterns?
This might solve your issue, I'm not sure. Worth a shot, I guess.