在django中上传图像:获取"未定义全局名称上下文"错误

Maj*_*eek 3 django image

我正在尝试使用django上传图像并遵循网站上的教程.在views.py我有:

def picture_upload(request):
    """
    form to upload an image together with a caption.
    saves it as a Picture in the database on POST.
    shows the last uploaded picture and let's you upload another.
    """
    picture = None
    if request.method != 'POST':
        form = PictureUploadForm()
    else:
        form = PictureUploadForm(request.POST, request.FILES)
        if form.is_valid():
            # an UploadedFile object
            uploadedImage = form.cleaned_data['image']
            caption = form.cleaned_data['caption']

            # limit to one database record and image file.
            picture, created = Picture.objects.get_or_create(picture_id=1)
            if not created and picture.get_image_filename():
                try:
                    os.remove( picture.get_image_filename() )
                except OSError:
                    pass

            # save the image to the filesystem and set picture.image
            picture.save_image_file(
                uploadedImage.filename, 
                uploadedImage.content
            )

            # set the other fields and save it to the database
            picture.caption = caption
            picture.save()

            # finally, create a new, empty form so the 
            # user can upload another picture.
            form = PictureUploadForm()

    return render_to_response(
        'example/picture_upload.html',
        Context(dict( form=form, last_picture=picture) ) )
Run Code Online (Sandbox Code Playgroud)

错误说:

全局名称'Context'未定义为"在我的代码的最后一行."views.up在picture_upload,第111行".

我怎么解决这个问题?

Yuj*_*ita 6

如果没有定义,则没有定义.您必须从django.template导入Context.

在文件顶部,输入

from django.template import Context
Run Code Online (Sandbox Code Playgroud)

你不能神奇地希望所有变量都被定义...... PictureUploadForm如果你没有导入它或者定义它,你认为你可以使用吗?

  • 有时我想我可以使用我没有输入的东西,因为我很特别. (2认同)