'的QueryDict'对象没有属性'标题'在django

时间:2015-05-04 16:40:18

标签: django django-views

我已经编写了这个简单的图片上传应用,用户应该可以为上传的图片添加标题。

观点是:

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

模型是:

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)

模板:

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

当我上传照片时,填写标题字段并提交表单,我得到:

'QueryDict' object has no attribute 'caption'

我尝试了不同的东西,而不是newpic.caption = request.POST.caption,但都没有效果。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

试试这个

app.use(categories);

request.POST['caption']

两者都从表单发布数据中获取标题值。通过指定标题的默认值,后者在我看来只是一种更安全的方式。