我收到了一个错误 / accounts / regist /上的NameError 全局名称'RegisterForm'未定义。
我确实定义了'RegisterForm'。 我在forms.py中写道
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
class RegisterForm(UserCreationForm):
def __init__(self, *args, **kwargs):
__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['password'].widget.attrs['classF'] = 'form-control'
在views.py中
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.http import require_POST
def index(request):
context = {
'user': request.user,
}
return render(request, 'accounts/index.html', context)
@login_required
def profile(request):
context = {
'user': request.user,
}
return render(request, 'accounts/profile.html', context)
def regist(request):
form = RegisterForm(request.POST or None)
context = {
'form': form,
}
return render(request, 'accounts/regist.html', context)
@require_POST
def regist_save(request):
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
return redirect('main:index')
context = {
'form': form,
}
return render(request, 'accounts/regist.html', context)
在urls.py中
from django.conf.urls import url
from . import views
from django.contrib.auth.views import login, logout
urlpatterns = [
url(r'^login/$', login,
{'template_name': 'registration/accounts/login.html'},
name='login'),
url(r'^logout/$', logout, name='logout'),
url(r'^regist/$', views.regist,name='regist'),
url(r'^regist_save/$', views.regist_save, name='regist_save'),
]
我该如何解决? 此外,我真的无法理解我没有在任何地方写全球。(我是初学者)
答案 0 :(得分:0)
您在forms.py中定义了它,但未将其导入views.py。
另请注意,您的__init__
方法不起作用;这不是你如何调用超类方法。您需要使用super
方法:
class RegisterForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
和LoginForm类似。
答案 1 :(得分:0)
添加此项 来自.forms import RegisterForm