python - Django 表單問題?
問題描述
關于Django表單問題先給出models.py和forms.py
圖片描述
再給出views.py的代碼
def articleUpdate(request, articleId):’’’Update the article instance: 1. Get the article to update; redirect to 404 if not found2. Render a bound form if the method is GET3. If the form is valid, save it to the model, otherwise render abound form with error messages’’’articleToUpdate = get_object_or_404( Article, id=articleId)template = ’article/articleCreateUpdate.html’if request.method == ’GET’: print(ArticleForm(instance=articleToUpdate)) articleForm = ArticleForm(instance=articleToUpdate) return render(request, template, {’articleForm’:articleForm, ’article’:articleToUpdate})# POSTarticleForm = ArticleForm(request.POST, instance=articleToUpdate)if not articleForm.is_valid(): return render(request, template, {’articleForm’:articleForm, ’article’:articleToUpdate})articleForm.save()messages.success(request, ’文章已修改’)return redirect(’article:articleRead’, articleId=articleId)def commentCreate(request, articleId): ’’’Create a new article instance1. If method is GET, render an empty form2 . If method is POST, perform form validation. Display error messages if the form is invalid3. Save the form to the model and redirect to the article page’’’template = ’article/commentCreate.html’ articleToUpdate = get_object_or_404( Article, id=articleId) if request.method == ’GET’:return render(request, template,{’commentForm’:CommentForm(), ’article’:articleToUpdate}) # POSTcommentForm = CommentForm(request.POST, instance=articleToUpdate) if not commentForm.is_valid():return render(request, template, {’commentForm’:commentForm(), ’article’:articleToUpdate}) commentForm.save() messages.success(request,’留言已新增’) return redirect(’article:articleRead’,articleId=articleId)
兩則方法是幾乎是一樣的,都是用forms表單,但是我使用的forms表單并不是同一類,一個是ArticleForm一個是CommentForm但是結果出現在views:commentCreate里它的效果是等于articleUpdate,即新增留言變成修改文章內容
問題解答
回答1:表單是類,你取出數據,為什么不填充到表單中。
else:form = CommentsForm(request.POST)if form.is_valid():
相關文章:
1. docker-compose中volumes的問題2. javascript - node安裝后,npm老是報不是內部命令,如何解決呢?3. .......4. 數據庫 - 使用讀寫分離后, MySQL主從復制延遲會導致讀不到數據嗎?5. CSS3的漸變屬性的疑惑6. python如何設置一個隨著系統時間變化的動態變量?7. javascript - 為什么js代碼后面報錯,會導致前面的代碼執行不了,我確定后面的部分和前面的部分沒有邏輯上的關聯。8. docker綁定了nginx端口 外部訪問不到9. 就一臺服務器,mysql數據庫想實現自動備份,如何設計?10. 請問一下,圖片上傳成功,但是后臺對應文件夾里面卻沒有圖片,這是什么原因?(已部署到服務器)
