Probleme mit dem Django-Formular?
为情所困
为情所困 2017-05-18 10:52:14
0
1
671

Informationen zu Django-Formularproblemen
Geben Sie zuerst models.py und forms.py an

Bildbeschreibung

Geben Sie uns noch einmal den Code von 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)

Die beiden Methoden sind fast gleich, sie verwenden beide Formulare, aber die Formulare, die ich verwende, sind nicht vom gleichen Typ, eines ist ArticleForm und das andere ist CommentForm, aber das Ergebnis erscheint in den Ansichten: commentCreate und seine Wirkung ist gleich der von ArticleUpdate , Das heißt, das Hinzufügen einer Nachricht ändert den Inhalt des Artikels

为情所困
为情所困

Antworte allen(1)
巴扎黑

表单是类,你取出数据,为什么不填充到表单中。

else:
        form = CommentsForm(request.POST)
        if form.is_valid():
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!