2017-04-15 30 views
0

我使用這個表單來添加和更新帖子。當我想編輯帖子並更新圖像時,如果帖子有圖像,Django會添加['圖像清除']複選框。但它不起作用。表單無效,如果我勾選複選框並選擇新的圖像。但如果我只選擇新的圖像(沒有勾選複選框)它的作品。Django窗體無效,當我試圖更新圖片

我在找什麼問題很長時間,但沒找到。你可以幫我嗎?很遺憾,我的英語

forms.py

class AddIdeaFrom(forms.ModelForm): 
class Meta: 
    model = Idea 
    fields = ['title', 'description', 'image'] 
title = forms.CharField(max_length=500, widget=forms.TextInput(attrs={'class': 'form-control'})) 
description = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class': 'form-control'})) 
image = forms.FileField(required=False) 

views.py

def idea_edit(request,idea_id): 

if request.method == "GET": 
    idea = Idea.objects.get(id=idea_id) 
    edit_idea = AddIdeaFrom(initial={'title':idea.title,'description':idea.description,'image':idea.image}) 
    return render(request, 'myidea/my/idea_edit.html', {'form':edit_idea, 'comment':idea.comment}) 

if request.method == "POST": 
    idea = Idea.objects.get(id=idea_id) 
    edit_idea = AddIdeaFrom(request.POST,request.FILES) 
    if edit_idea.is_valid(): 
     edit_idea = AddIdeaFrom(request.POST, request.FILES, instance=idea) 
     if edit_idea.has_changed(): 
      new_idea = edit_idea.save() 
      new_status = Status.objects.get(name = STATUS_REVIEW) 
      new_idea.status = new_status 
      new_idea.save() 
      return redirect('/') 
     else: 
      return HttpResponse('Need some changes') 
    else: 
     form = AddIdeaFrom(instance= idea) 
     return render(request, 'myidea/my/idea_edit.html', {'form': form}) 

HTML

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

     <label for="description.for_label" class="col-sm-9">Text</label> 
      {{ form.description }} 

     <label for="description.for_image" class="col-sm-9">Choose Image</label> 
     {{ form.image }} 

     <button type="submit" class="btn btn-space mb-">Add</button> 
    </div> 
</form> 
</div> 
+0

你可以編輯帖子,驗證錯誤嗎?嘗試這樣的事情:print(edit_idea.errors) – Bulva

+0

我嘗試在我的模板中使用{{form.errors}},但沒有任何反應 – Ilya

+0

哦......它的工作原理:「請上傳文件或選中」Clear「 ,但不要同時做這兩件事。「現在一切都很清楚,謝謝 – Ilya

回答

0

從您的評論看起來你有問題,在矛盾的數據你形成。這可能是因爲使用「清除」複選框與FileField小部件。試試這個在你的forms.py

image = forms.FileField(widget=FileInput, required=False) 

這應該從您的窗體中刪除「清除」複選框。 或者如果您不想讓用戶清除圖像,則可以在驗證前取消選中該圖像。