【问题标题】:Uploading image in django: getting "global name context is not defined" error在 django 中上传图像:出现“未定义全局名称上下文”错误
【发布时间】:2012-08-17 08:52:42
【问题描述】:

我正在尝试使用 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) ) )

错误提示:

全局名称“上下文”未定义”在我的代码的最后一行。“views.py in picture_upload, line 111”。

我该如何解决这个问题?

【问题讨论】:

    标签: django image


    【解决方案1】:

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

    在文件顶部,输入

    from django.template import Context
    

    您不能神奇地希望所有变量都已定义...如果您没有导入它或以其他方式定义它,您认为可以使用PictureUploadForm 吗?

    【讨论】:

    • 有时我喜欢认为我可以使用我没有导入的东西,因为我很特别。
    • 其实这里根本不用Context。 render_to_response(和较新的render)对普通的字典非常满意。
    • 确保从 django.template 导入上下文 - 上下文都是小写的 - 使用 C 时它不起作用。谢谢你帮助了我。
    猜你喜欢
    • 2013-06-07
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 2014-08-17
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多