2016-11-06 181 views
0

每當我運行終端服務器時,即使定義了它並將其命名,我總是會得到「無法導入名稱」的問題。Django無法導入名稱

這裏是我的views.py

from django.http import HttpResponse 
import datetime 

def current_datetime(request): 
    now = datetime.datetime.now() 
    html = "<html><body>It is nose %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) 

,這裏是我的urls.py是應該稱它爲但得到錯誤hours_ahead

from django.http import HttpResponse 
from django.contrib import admin 
from mysite.views import current_datetime, hours_ahead 

urlpatterns = patterns('', 
     (r'^time/$', current_datetime), 
     (r'^time/plus/(\d{1,2})/$', hours_ahead), 
) 

回答

2

試試這個。

from django.conf.urls import include, url 
from django.contrib import admin 
from . import views 

urlpatterns = [ 
    url(r'^time/$', views.current_datetime), 
    url(r'^time/plus/(\d{1,2})/$', views.hours_ahead) 
] 

如果這不起作用。請將錯誤堆棧添加到您的問題中。

+0

謝謝,但現在它說模式沒有被定義 - 參見:{urlpatterns = patterns('', NameError:name'patterns'is not defined} – Bryn

+3

'patterns'在Django 1.10中被移除如果你正在使用Django 1.8+,將其更改爲'urlpatterns = [url(...),...]' – Alasdair

+0

現在它是說url沒有被定義從django.http導入HttpResponse 從django.contrib導入管理 從mysite。您可以從.import視圖導入current_datetime urlpatterns = [url( (r'^ time/$',views.current_datetime), (r'^ time/plus /(\ d {1,2})/ $ ',views.hours_ahead))] – Bryn