Django - 未定义全局名称错误

时间:2014-12-03 19:39:05

标签: python django

我有NameError: global name 'CreateMapForm' is not defined错误,但是间歇性的

我不明白,因为我的python IDE中的一切似乎都很好。 CreateMapForm只是一个简单的ModelForm。任何人都可以指出这个问题的原因或建议在哪里寻找原因?

地图/ views.py:

from maps.forms import *

@login_required(login_url='/accounts/login/')
def createMap(request, folder_id):
    folder = Folder.objects.get(pk=folder_id, created_by=request.user)

    if type(folder) != Folder:
        folder = folder.parent

    nodes = folder.get_ancestors(include_self=True)

    form = CreateMapForm() #this line cause the error
    html = render_to_string("basqui/manage_maps_create.html", {'folder': folder, 'nodes': nodes, 'form': form}, context_instance=RequestContext(request))
    response = json.dumps({'html': html})

    if request.POST:
        form = CreateMapForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.created_by = request.user
            instance.parent = folder
            instance.save()
            response = json.dumps({"map": {"pk": instance.pk, "name": instance.name}}, cls=DjangoJSONEncoder)
        else:
            html = render_to_string("basqui/manage_maps_create.html", {'folder': folder, 'nodes': nodes, 'form': form}, context_instance=RequestContext(request))
            response = json.dumps({'html': html})

    return HttpResponse(response, content_type="application/json")

地图/ forms.py

from django import forms
from maps.models import *

class CreateMapForm(forms.ModelForm):
    class Meta:
        model = BasquiMap
        fields = ('name', 'layers', 'wms')

1 个答案:

答案 0 :(得分:3)

如果CreateMapForm()中有forms,您需要在views中导入它,因此请将以下内容添加到views

from maps import forms 

并替换以下内容:

form = CreateMapForm()

with:

form = forms.CreateMapForm()