尝试通过HTTP请求(GET)将数据呈现到表单时出错

时间:2019-07-23 04:39:59

标签: python django django-forms

我是Django和构建表单的新手。我有几个有关如何完成简单操作的示例,并将在下面共享代码

models.py

form Django.db import models

class Query(models.Model):
    query_name = models.CharField(max_length=40, null=True, blank=True)

forms.py

from django import forms
from testUI.models import Query

class QueryForm(forms.ModelForm):

    class Meta:

        model = Query

        fields = ['query_name']

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import Query

def queries(request):

if request.method == "GET":
   query = Query.objects.all()
   return render(request, 'testUI/queries.html', {"form": query})
else:
    query_form = QueryForm(request.POST)
    if query_form.is_valid():
        query_form.save()
        return render(request, 'testUI/queries.html', {"form": query_form})
    else:
        return HttpResponse("Form is not valid)

queries.html

{% extends "testUI/base.html" %}
{% block content %}
<div class="page-header" style="...">
    <button type="button" data-toggle="modal" data-target="#newQueryModal" class="btn btn-success" sytle="..."><i class="fas fa-plus"></i>New Query</button>
</div>

<div>
  <div class="modal-dialog modal-xl" role="document">
     <table class="table">
        <thead>
           <th>Query Name</th>
        </thead>
        <tbody>
           {% for query in form }
           <tr>
             <td>{{query.query_name}}</td>
           </tr>
        </tbody>
      </table>
      <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form }}<br>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-success">Save Query</button>
      </form>
    </div>
  </div>

  {% endblock %}

urls.py

from django.urls import path

from . import views

urlpatterns = [
   path('queries/', views.queries, name='queries')
]

使用外壳创建一条记录。我在页面呈现时看到的是

想法?

1 个答案:

答案 0 :(得分:0)

这样更改您的视图:

  def queries(request):
    if request.method == "POST":
        query_form = QueryForm(request.POST or None)
        if query_form.is_valid():
            query_form.save()
            return redirect('somewhere')
        else:
            return HttpResponse("Form is not valid)
    else:
        query = Query.objects.all()
        query_form = QueryForm()
    return render(request, 'testUI/queries.html', {"queries": query,'form':query_form})

然后在模板中获取如下查询:

 <tbody> 
       <tr>{% for query in queries %}
         <td>{{query.query_name}}</td>
          {% endfor %}
       </tr>
    </tbody>