我当前正在尝试实现登录和注销到django站点的功能,并且在虚拟环境中尝试使用python manage.py runserver命令时遇到以下错误。我正在使用django 2.2
我的对象:
realtime
|-core
|-nodejs
|-realtime
|-templates
| |-index.html
|-url.py
我的代码url.py
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views
urlpatterns = [
url(r'Home/$', views.Home, name='Home'),
url(r'^node_api$', views.node_api, name='node_api'),
url(r'^accounts/login/$', auth_views.LoginView.as_view(template_name='myapp/login.html')),
url(r'^login/$', views.LogoutView.as_view(template_name=template_name), name='logout'),
]
core \ views.py
from core.models import Comments, User
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseServerError
from django.views.decorators.csrf import csrf_exempt
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators import login_required
import redis
@login_required
def home(request):
comments = Comments.objects.select_related().all()[0:100]
return render(request, 'index.html', locals())
@csrf_exempt
def node_api(request):
try:
#Get User from sessionid
session = Session.objects.get(session_key=request.POST.get('sessionid'))
user_id = session.get_decoded().get('_auth_user_id')
user = User.objects.get(id=user_id)
#Create comment
Comments.objects.create(user=user, text=request.POST.get('comment'))
#Once comment has been created post it to the chat channel
r = redis.StrictRedis(host='localhost', port=6379, db=0)
r.publish('chat', user.username + ': ' + request.POST.get('comment'))
return HttpResponse("Everything worked :)")
except Exception as e:
return HttpResponseServerError(str(e))
答案 0 :(得分:3)
在线
url(r'Home/$', views.Home, name='Home'),
视图Home
是从模块views
加载的,该模块引用了此导入:
from django.contrib.auth import views
由于django.contrib.auth.views
未定义任何类或函数Home
,因此会出现错误。
您可能忘记了导入应用程序的views
模块:
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
import core.views as my_app_views
urlpatterns = [
url(r'Home/$', my_app_views.home, name='Home'),
url(r'^node_api$', my_app_views.node_api, name='node_api'),
url(r'^accounts/login/$', auth_views.LoginView.as_view(template_name='myapp/login.html')),
url(r'^login/$', auth_views.LogoutView.as_view(template_name=template_name), name='logout'),
]
请注意,在此新版本中,django.contrib.auth.views
的导入名称为auth_views
,而自定义应用的views
的导入名称为my_app_views
。这样可以避免从一个应用程序或另一个应用程序调用视图时出现任何混乱