如何在Django中使用modelForm时部分更新对象?

时间:2014-12-11 18:14:05

标签: django django-forms

我想让用户在不更改照片的任何其他字段的情况下添加/更新已更新照片的标题。

以下是模型:

class UserPic(models.Model):
    user = models.ForeignKey(User, unique=False)
    picfile = ImageWithThumbsField(upload_to= get_uplaod_file_name, sizes=((648,648),(200,200),(1200,1200)))
    caption = models.CharField(max_length=200 , blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    likes = models.IntegerField(default=0)
    liked_by= models.ForeignKey(Liker, blank=True)

    @models.permalink
    def get_absolute_url(self):
        return ('view_pirate', None, {'user': self.account.user})    

    def __unicode__(self):
        return unicode(self.picfile.name) 

views.py

def edit_photo(request, pic_id):
    pic = UserPic.objects.get(id=pic_id)
    if request.method == 'POST':        
         if pic.user== request.user:
            picform = CaptionForm(request.POST)
            if picform.is_valid():
                edform = picform.save(commit=False)
                edform.caption = request.POST['caption']
                edform.save()
                message = "caption is uploaded" 


    else:
        edform = CaptionForm() 

    args = {}
    args.update(csrf(request))
    args['pic'] = pic
    args['pic_id'] = pic_id
    #args['form'] = edform

    return render_to_response('userpics/photo.html', args,    
                              context_instance= RequestContext(request))

photo.html

<div class="caption">
        <form action="{% url "userpics.views.edit_photo" pic.id %}" method="POST">
        {% csrf_token %}            
        {{form.as_ul}}           
        <input type="submit" value="SEND">
        </form>

forms.py:

class CaptionForm(forms.ModelForm):    
        class Meta:
                model= UserPic
                fields = ('caption',)

然而,当我发布表格时,django仍抱怨:

MultiValueDictKeyError at /pics/edit/26
"'caption'"

我真的很困惑,因为我找不到任何资源来处理这个特殊问题。非常感谢您的提示。

1 个答案:

答案 0 :(得分:0)

好的,我设法解决了这个问题:

photo.html

    <form action="{% url "userpics.views.edit_photo" pic.id %}" method="POST">
        {% csrf_token %}
        <input type="text" name="caption" value="{{pic.caption}}">
        <input type="submit" value="SEND">
    </form>

views.py

def edit_photo(request, pic_id):
    pic = UserPic.objects.get(id=pic_id)
    if request.method == 'POST':        
         if pic.user== request.user:
            picform = CaptionForm(request.POST)             
            if picform.is_valid():
                pic.caption = request.POST['caption']
                pic.save()
                message = "caption is uploaded" 

    else:
        edform = CaptionForm(instance=pic) 

    args = {}
    args.update(csrf(request))
    args['pic'] = pic
    args['pic_id'] = pic_id

    return render_to_response('userpics/photo.html', args,    
                              context_instance= RequestContext(request))