0

我正在关注 DjangoBook 教程,但在第 14 章(用户注册)中遇到了问题

django.contrib.auth.forms中有一个UserCreationForm类。我正在尝试创建一个基于UserCreationForm调用的新类RegisterForm

这是我RegisterFormdjango.contrib.auth.forms中的课程

class RegisterForm(UserCreationForm):
    email = forms.EmailField(label="Email")
    fullname = forms.CharField(label="Full name")

    class Meta:
        model= User
        fields = ("username","fullname","email",)

这是视图功能

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/books/")
    else:
        form = RegisterForm(UserCreationForm)
    return render(request, "registration/register.html", {
        'form': form,
    })

我不知道为什么我得到一个 ImportError ,它指出我无法RegisterForm在我的视图中导入名称,有人可以帮助我谢谢。

这是我的堆栈跟踪

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/register/

Django Version: 1.5.1
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.admin',
'mysite.books')
Installed Middleware:
 ('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
103.                     resolver_match = resolver.resolve(request.path_info)
File "C:\Python27\lib\site-packages\django\core\urlresolvers.py" in resolve
319.             for pattern in self.url_patterns:
File "C:\Python27\lib\site-packages\django\core\urlresolvers.py" in url_patterns
347.         patterns = getattr(self.urlconf_module, "urlpatterns",                      self.urlconf_module)
File "C:\Python27\lib\site-packages\django\core\urlresolvers.py" in urlconf_module
342.             self._urlconf_module = import_module(self.urlconf_name)
File "C:\Python27\lib\site-packages\django\utils\importlib.py" in import_module
35.     __import__(name)
File "C:\Users\Ray Lim\Desktop\project\home\username\djcode\mysite\mysite\urls.py" in    <module>
14. from mysite.books import views
File "C:\Users\Ray    Lim\Desktop\project\home\username\djcode\mysite\mysite\books\views.py" in <module>
11. from django.contrib.auth.forms import RegisterForm

Exception Type: ImportError at /register/
Exception Value: cannot import name RegisterForm
4

1 回答 1

1

Django 1.5开始,模块中没有这种形式django.contrib.auth.forms.

您可能希望使用能够为您突出显示此类内容的编辑器。比如PyCharm

不过,重点是,您至少应该对要学习的内容有基本的Python了解Django。你看,这些陈述

class RegisterForm(UserCreationForm)    
    ...
# And then:
form = RegisterForm(UserCreationForm) 

从 Python 的角度来看几乎没有任何意义。

您正在编写 Python 代码。在 Python 中。你必须学习 Python。是的,可以走另一条路,但要困难得多。

于 2013-05-02T07:20:35.320 回答