未定义/ accounts / upload_save /全局名称'ContactForm'的NameError

时间:2017-09-24 13:52:41

标签: python django

我在/ accounts / upload_save /收到错误,NameError 全局名称'ContactForm'未定义。 我正在制作照片上传系统。 现在views.py就像

def upload(request, p_id):
    form = UserImageForm(request.POST or None)
    d = {
        'p_id': p_id,
        'form':form,
    }
    return render(request, 'registration/accounts/photo.html', d)

@csrf_exempt
def upload_save(request):

    photo_id = request.POST.get("p_id", "")

    if (photo_id):
        photo_obj = Post.objects.get(id=photo_id)
    else:
        photo_obj = Post()

    files = request.FILES.getlist("files[]")

    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('registration/accounts/photo.html')
    else:

        photo_obj.image = files[0]
        photo_obj.image2 = files[1]
        photo_obj.image3 = files[2]

        photo_obj.save()

        photos = Post.objects.all()
        context = {
            'photos': photos,
        }
        return render(request, 'registration/accounts/photo.html', context)

Traceback说

Traceback:

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

File "/Users/xxx/Downloads/KenshinServer/accounts/views.py" in upload_save
  120.         form = ContactForm(request.POST)

Exception Type: NameError at /accounts/upload_save/
Exception Value: global name 'ContactForm' is not defined]

之前,我在files = request.FILES.getlist(“files []”)中得到索引超出范围错误,我可以理解为什么这个错误发生空文件导致它。所以,我试图使用ContactForm并写道通过在django文档中查看示例代码我的代码。但是,我收到此错误,我无法理解为什么会发生此错误。我想在文件为空时加载photo.html& upload方法。如何修复此问题?

1 个答案:

答案 0 :(得分:1)

如果我没错,您可以尝试将某些教程用作系统的模板。像这样official one

您应该在forms.py中define a Form class并导入它以使用其form_valid()方法。