Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading image in django: getting "global name context is not defined" error

Tags:

image

django

I am trying to upload an image using django and following a tutorial from a website. In views.py I have:

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) ) )

The error says:

global name 'Context' is not defined" at last line of my code. "views.py in picture_upload, line 111".

How can I solve this problem?

like image 820
MajorGeek Avatar asked Dec 01 '25 09:12

MajorGeek


1 Answers

If its not defined, it's not defined. You'd have to import Context from django.template.

At the top of your file, type in

from django.template import Context

You can't magically hope that all variables are defined... would you think you could use PictureUploadForm if you had not imported it or otherwise defined it?

like image 87
Yuji 'Tomita' Tomita Avatar answered Dec 04 '25 00:12

Yuji 'Tomita' Tomita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!