Jand
Jand

Reputation: 2727

'QueryDict' object has no attribute 'caption' in django

I have written this simple image upload app, where users should be able to add caption to the uploaded image.

the views is:

@login_required
def upload(request):
    thisuser =User.objects.get(username = request.user.username)

    args= {}

    if request.method == 'POST':
        picform = PicForm(request.POST, request.FILES)
        if picform.is_valid():
            newpic = UserPic(picfile = request.FILES['picfile'])
            newpic = picform.save(commit=False)
            newpic.user_id = request.user.id
            newpic.caption = request.POST.caption # <--problematic line
            newpic.save()
            message = "file %s is uploaded" % newpic

            args['pic'] = newpic.picfile
            args['caption'] = newpic.caption

    else:
        picform = PicForm()  

    args.update(csrf(request))
    args['picform'] = picform    

    return render_to_response('pics/upload.html',args,
        context_instance=RequestContext(request))   

The model is:

class UserPic(models.Model):
    user = models.ForeignKey(User, unique=False)
    picfile = ImageWithThumbsField(upload_to= get_uplaod_file_name,sizes=((200,200),))
    caption = models.TextField(max_length=200 , blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

And the template:

<div>   
Upload New picture

        <form action="/pics/upload/" method="post" enctype="multipart/form-data">
            {% csrf_token %}

        <ul  class="list-unstyled  form-group">
    {{picform.as_ul}}
        </ul>
            </p>
            <p><input type="submit" value="Upload" /></p>
        </form>
 </div> 

When I upload photo, fill the caption field and submit the form,, I get:

'QueryDict' object has no attribute 'caption'

I tried different things instead of newpic.caption = request.POST.caption but none worked. So appreciate your help.

Upvotes: 4

Views: 10907

Answers (1)

Pieter Hamman
Pieter Hamman

Reputation: 1612

Try this

request.POST['caption']

or

request.POST.get('caption', 'Default').

Both get the caption value from the form post data. The latter is just a safer way in my opinion by specifying a default value for caption.

Upvotes: 14

Related Questions