0

我正在尝试将表单添加到我的 django 视图中。问题是,我不能声明类。那就是问题所在:

在此处输入图像描述

Addform.py

from django import forms

class AddSubjectForm(forms.Form):
def __init__(self):
    pass

name = forms.CharField(max_length=200)

Views.py

from django.http import HttpResponse
from django.template import Context, loader
from AddSubject.AddForm import AddSubjectForm

def index(request):
    template = loader.get_template('AddSubject/index.html')

    if request.method == 'POST':
        form = AddSubjectForm()
        context = Context({
                       'form': form,
                       })
    else:
        form = AddSubjectForm()
            context = Context({        
                       'form': form,
                       })

    return HttpResponse(template.render(context))

最后我收到错误:

Environment:


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

Django Version: 1.5.1
Python Version: 2.7.5
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'AddSubject')
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
115.                         response = callback(request, *callback_args, **callback_kwargs)
File "blablabla\AddSubject\views.py" in index
14.         form = AddSubjectForm()

Exception Type: TypeError at /AddSubject/
Exception Value: 'module' object is not callable

我在 Google 中寻找解决方案,但每个回复都是关于文件名的。它对我不起作用:/您有什么想法,为什么 AddSubjectForm 不起作用?

4

1 回答 1

3

根据我的评论,您的导入声明是错误的。

你写的是

from AddSubject.AddForm import AddSubjectForm

将其更改为

from AddFrom import AddSubjectForm

usingfrom所做的是遍历所有模块,以便它可以从相关模块导入。但是由于AddSubject不是其中的包,AddSubject而是从模块加载并将包视为模块。

在这里可以找到很好的阅读:简单语句#import

于 2013-06-10T09:00:47.697 回答