我试图在views.py中定义一个继承泛型视图的类。代码如下。在运行服务器上我得到错误 class UserFormView(View): NameError:name' View'未定义
虽然我已导入通用。请让我知道原因。
from django.views import generic
from django.utils import timezone
from django.shortcuts import render, get_object_or_404,render_to_response,redirect
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.contrib.auth import authenticate,login
from django.core.context_processors import csrf
from .forms import UserForm
# Create your views here.
def home(request):
return render(request, 'fosssite/home.html')
def login(request):
c={}
c.update(csrf(request))
return render_to_response('fosssite/login.html',c)
class UserFormView(View):
form_class=UserForm
template_name='fosssite/signup.html'
def get(self,request):
form=self.form_class(None)
return render(request,self.template_name,{'form':form})
#validate by forms of django
def post(self,request):
form=self.form_class(request.POST)
if form.is_valid():
# not saving to database only creating object
user=form.save(commit=False)
#normalized data
username=form.cleaned_data['username']
password=form.cleaned_data['password']
#not as plain data
user.set_password(password)
user.save() #saved to database
def auth_view(request):
username=request.POST.get('username', '')
password=request.POST.get('password', '')
user=auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request,user)
return HttpResponseRedirect('/loggedin')#url in brackets
else:
return HttpResponseRedirect('/invalid')
def loggedin(request):
return render_to_response('fosssite/loggedin.html',{'fullname':request.user.username})
def logout(request):
auth.logout(request)
return render_to_response('fosssite/logout.html')
def invalid_login(request):
return render_to_response('fosssite/invalid_login.html')
`
答案 0 :(得分:3)
View
名称需要导入。添加以下import语句:
from django.views.generic import View
或者使用
中已导入的generic
模块
class UserFormView(generic.View)
# ^
答案 1 :(得分:1)
您需要明确导入View
:
from django.views.generic import View
或将其称为generic.View
:
class UserFormView(generic.View):
# ...
答案 2 :(得分:0)
from my_app import views
例如代码:
<强> urls.py 强>
from django.conf.urls import url
from django.contrib import admin
from pro1 import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^admin/', admin.site.urls),
]
<强> views.py 强>
from django.shortcuts import render
def home(request):
template="home.html"
context={}
return render(request,template,context)
猜它会解决问题。