Django 模型表单不保存数据

Django Model Form not saving data

我正在开发 Django 应用程序,我正在尝试为用户的建议和评论创建表单。我想在数据库(管理界面)中看到 suggestions/comments。评论提交后,不会保存在数据库中。我在这里有一些错误,但我不知道它在哪里。你能帮帮我吗?

views.py:

def komentariPrijedlozi(request):
    if request.method == 'POST':
        form = CommentsSuggestionsForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'rjecnik/successCommentsSuggestions.html')
    form = CommentsSuggestionsForm()
    context = {'form' : form}
    return render(request, 'rjecnik/komentariPrijedlozi.html', context)

komentariPrijedlozi.html:

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Comments and suggestions</title>
</head>

<body>
  <section class="main-container1" style=" margin-top: 50px; background-color: lightgray;">
    
      <div class="columns">
      <div class="main-par" style="font-size: 21px; margin-bottom: 20px;">Komentari i prijedlozi novih prijevoda:</div>
        <div class="column is-half is-offset-one-quarter">

          
          <form method="POST" autocomplete="off" enctype="multipart/form-data">
    <tr>
        <th>
          <label for="suggestion1">Prijedlog novog pojma:</label>
        </th>
        <td >
           <input type="text" name="suggestion1" maxlength="100" autocomplete="off" style="width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block;">
        </td>
    </tr>
    <tr>
        <th>
          <label for="suggestion2">Prijedlog prijevoda:</label>
        </th>
        <td>
          <input type="text" name="suggestion2" maxlength="100" autocomplete="off" style="width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block;">
            
        </td>
    </tr>
    <tr>
        <th>
            <label for="comment">Komentar:</label>
        </th>
        <td>
            <textarea name="comment" cols="40" rows="10" style="width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block;"></textarea>
        </td>
    </tr>

          {% csrf_token %}
          <input type="submit" class="btn-sub" value="Submit">
       
         </form>
        </div>
      </div>
    </div>
  </section>
</body>

</html>

models.py:

 class CommentsSuggestions(models.Model):
    suggestion_word = models.CharField(max_length=100)
    suggestion_translation = models.CharField(max_length=100)
    comment_suggestion = models.TextField()

forms.py:

class CommentsSuggestionsForm(ModelForm):
class Meta:
    model = CommentsSuggestions
    fields = '__all__'

urls.py:

path('komentari_i_prijedlozi/', views.komentariPrijedlozi, name="komentariPrijedlozi"),

据我所知,您没有在模板中使用自定义表单,请将模板中的表单更改为:

<form method="POST" autocomplete="off" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_table }}
    <input type="submit" class="btn-sub" value="Submit">
</form>

然后这些值将在到达您的 views.py 时得到正确处理。