python - Django 表單問題?
为情所困
为情所困 2017-05-18 10:52:14
0
1
728

關於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 found
2. Render a bound form if the method is GET
3. If the form is valid, save it to the model, otherwise render a
bound 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})
# POST
articleForm = 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 instance
1. If method is GET, render an empty form
2 . If method is POST, perform form validation. Display error messages if the form is invalid
3. 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})
    # POST
    
    commentForm = 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():
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板