Django 1.7: some_name() takes exactly 2 arguments (1 given)

倖福魔咒の 提交于 2019-12-25 18:32:28

问题


this is my view.py

from django.http import HttpResponse
import datetime
def current_datetime(request):
     now = datetime.datetime.now()
     html = "<html><body>It is now %s.</body></html>" % now
     return HttpResponse(html)
def hours_ahead(request, offset):
     offset = int(offset)
     dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
     html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
     return HttpResponse(html)

this is my urls.py

from django.conf.urls import patterns, url, include
from mysite.view import current_datetime, hours_ahead
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),

# url(r'^admin/', include(admin.site.urls)),
(r'^time/$', current_datetime),
#(r'^time/plus/\d{1,2}/$', hours_ahead),
url(r'$', 'mysite.view.hours_ahead', name='hours_ahead'),
)

when i try to go to this localhost:8000/time/plus/24/ I have the error hours_ahead() takes exactly 2 arguments (1 given)


回答1:


You need to capture the offset from the url:

url(r'^time/plus/(\d+)/$', 'mysite.view.hours_ahead', name='hours_ahead'),

where (\d+) is a capturing group that would capture one or more digits. In case of localhost:8000/time/plus/24/ it would capture 24.




回答2:


offset is missing here:

url(r'$', 'mysite.view.hours_ahead', name='hours_ahead'),


来源:https://stackoverflow.com/questions/26113260/django-1-7-some-name-takes-exactly-2-arguments-1-given

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!