I am getting the following error when running my code:
File "C:\Users\emanull\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'current_datetime'
My file views.py:
from django.shortcuts import render
from django.http import HttpResponse
from datetime
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
My file urls.py:
from django.contrib import admin
from django.urls import include, path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('time/', include('views.current_datetime'))
]
CodePudding user response:
You have an error in your views.py file. The from datetime
is incorrect since you are not importing anything from the datetime package.
The correct usage in your case would be import datetime
.
Your second error is how you are using the URLs. This needs to be:
from django.contrib import admin
from django.urls import include, path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('time/', views.current_datetime, name='current-datetime'),
]
See the Django documentation for URLs for further reading.
CodePudding user response:
My file views.py:
from django.shortcuts import render
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)
My file urls.py:
from django.contrib import admin
from django.urls import include, path
from gogle import views
urlpatterns = [
path('admin/', admin.site.urls),
path('time/', views.current_datetime)
]
In your
views.py
you can either:from datetime import datetime
and usedatetime.now()
or
import datetime
and usedatetime.datetime.now()
In your
urls.py
use an absolute import along with the correct syntax according to the docs (include expects a localurls.py
not a view).
Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
CodePudding user response:
Two things you need to do.
fix the below line in your import code, replace
from datetime
byimport datetime
make sure you have the blank init.py file located in the same folder where views.py is, and then you can do like below:
from . import views urlpatterns = [ path('time/', include('views.current_datetime')) ]