python - 无法导入名称 'views' 、.Python、Django

标签 python django

我在这个论坛上阅读了很多答案,但它们并没有解决我的问题。我将非常感谢您的帮助。

我的文件views.py返回此错误:

from . import views
ImportError: cannot import name 'views' from '__main__' (C:/Users/tymot/Desktop/weather app/env/Environemnt/the_weather/weather/views.py)

views.py (Environemnt\the_weather\weather)

from django.shortcuts import render
from django.contrib import admin

def index(request):
    return render(request, 'weather/index.html') #returns the index.html 

urls.py (Environemnt\the_weather\weather)

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index),  #the path for our index view
]

urls.py (Environemnt\the_weather\the_weather)

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('weather.urls')),

模板(the_weather\weather\templates\weather) 仅文件index.html

目录

-the_weather
--the_weather
---__init__
---setting
---urls
---wsgi
--weather
---migrations
----__init__
---templates
----weather
-----index
---__init__
---admin
---apps
---models
---tests
---urls
---views
--db
--manage.py

我尝试使用from __future__ importabsolute_import主页导入 View 来解决我的问题。我还尝试将views.py复制到目录模板(并修改其代码),但不幸的是它不起作用

最佳答案

您需要将您的 View url分开,在您的应用程序中创建一个新模块(文件)urls.py,在您的情况下是 weather 文件夹,并在其中添加这些代码,并将其从 views.py 中删除,您可以读取 here以便更好地理解它。

路径:the_weather/weather/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index),  #the path for our index view
]

路径:the_weather/weather/views.py

from django.shortcuts import render
from django.contrib import admin

def index(request):
    return render(request, 'weather/index.html') #returns the index.html template

关于python - 无法导入名称 'views' 、.Python、Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51327457/

相关文章:

python - Azure Python Flask应用程序-AD身份验证问题

Django 模型表单集显示数据库数据而不是空表单集

python - Django:如何读取嵌套的 url 正则表达式

python - 创建新用户时出现属性错误

python mock.mock_reset() 返回模拟而不是重置模拟

python - 如何在python中执行shell命令?

python - Django Queryset 切片对数据库进行多次查询

python - 自定义选项卡中的 Django admin StackedInline

python - -0.0 和 +0.0 之间有区别吗?

python - 在 Python 中创建垂直 NumPy 数组