Django休息框架,序列化程序 - 用POST方法提交后不会返回主页

时间:2018-05-31 17:22:44

标签: python django django-rest-framework

我是这里的django新手。我很困惑,为什么在我提交了一个POST请求之后,django rest框架会引导我到这里这个页面

enter image description here

而不是让我回到我的主页

这是我的 views.py:

class TableData(APIView):
  def post(self,request,*args,**kwargs):
    startRange = request.POST.get('mcap')
    endRange = int(startRange) + 29868
    sector = request.POST['cat']
    print(str(sector))
    stocks =  StockInfo.objects.filter(Q(company__company_categories__contains=sector),Q(companymcap__range=(startRange,endRange)),Q(datetimecollect__contains=datetime.date(2018,3,13)))
    serializer = TableSerializer(stocks,many=True)
    return Response(serializer.data)

我的serializers.py:

class TableSerializer(serializers.ModelSerializer):

    #stocks = serializers.StringRelatedField(many=True)

    company_name = serializers.CharField(source='company.company_name')
    company_id = serializers.IntegerField(source='company.company_id')
    company_categories = serializers.CharField(source='company.company_categories')
    class Meta:
        model = StockInfo
        fields = ('company_name', 'company_id', 'company_categories','companyprice', 'companyvolume', 'companyeps', 'companydps', 'companynta', 'companype', 'companydy', 'companyroe', 'companyptbv', 'companymcap')

我最初的想法是,一个人从我的html表单中选择了一些标准,然后当他们提交表单时,我将根据他们的标准查询数据库并将其加载到序列化程序中。然后使用序列化程序在我的html页面中填充我的ajax数据表。

我尽我所能,但我仍然不知道出了什么问题......

EDITED

让我说如果我和ajax datatable一起使用...我是否仍然像我重定向我的页面一样这样做? 在我的mypage.html

中的ajax数据表的片段中
$(document).ready(function() {
                                        var table = $('#datatable').dataTable( {
                                             "processing": true,
                                             "searching": false,
                                             "ajax": {
                                                 "processing": true,
                                                 "url": "{% url 'tableData' %}",
                                                 "dataSrc": ""
                                             },

                                             "columns": [
                                                     { "data": "company_name" },
                                                     { "data": "company_id" },
                                                     { "data": "companyprice" },
                                                     { "data": "companyvolume" },
                                                     { "data": "companyeps" },
                                                     { "data": "companydps" },
                                                     { "data": "companynta" },
                                                     { "data": "companype" },
                                                     { "data": "companydy" },
                                                     { "data": "companyroe" },
                                                     { "data": "companyptbv" },
                                                     { "data": "companymcap" }
                                                 ]
                                         } );
                                     } );

网址:{%url'tableData'%}将指向url / api / table / data。

再次编辑

这是我的html模板

         <!-- Page Content Holder -->
{% extends "app/header.html" %}
{%load rest_framework%}
{% block nav_home%}
class="active"
{% endblock %}
{% block content %}
        <div id="content">              
            <nav class="navbar navbar-default">
                <div class="container" style="display: inline;">
                    <div class="row">
                        <ul class="navbar-nav px-3 ml-auto" style="display:inline-block;">
                            <li class="nav-item text-nowrap d-flex flex-row">
                            <div>
                                <i class="fa fa-sign-out-alt"><a href="{% url 'register' %}"> Sign Out</a></i>
                            </div>
                            </li>
                        </ul>
                    </div>
                    <br>
                    <div class="row">
                        <div class="col">
                            <div class="navbar-header">
                                <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">
                                    <i class="fa fa-bars"></i>
                                </button>
                            </div>
                        </div>                      
                        <div class="col-xl-10">
                            <form action="{% url 'stock' %}" method='GET'>
                                <div class="input-group">
                                    <input class="form-control border-secondary py-2" type="search" value="{{ request.GET.q }}" name="q" placeholder="Search ticker">
                                    <div class="input-group-append">
                                        <button class="btn btn-outline-secondary" type="button">
                                            <i class="fa fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </nav>

            <div class="row">
              <div class="col-xl-10">
                <div class="card" style="width: 1070px;">
                  <div class="card-body">

                    <h5 class="card-title">Uptrend Prediction</h5>
                    <br>
                    <div class="dropdown">
                      <button class="btn btn-info dropdown-toggle btn-outline-info waves-effect" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Categories
                      </button>

                      <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                        <a class="dropdown-item" href="#">Most Active</a>
                        <a class="dropdown-item" href="#">Least Active</a>
                        <a class="dropdown-item" href="#">Top Gainers</a>
                        <a class="dropdown-item" href="#">Top Losers</a>
                      </div>
                    </div>
                    <br>
                    <form action="{% url 'tableData' %}" method="POST"><!--start of formquery-->
                        <div class="container">
                        <div class="row">
                            <div class="col-2">
                            <h2 style="font: 16px Helvetica Neue,Helvetica,Arial,sans-serif; margin: 0.5em;">Market Cap:</h2>
                            </div>
                            <div class="col-6">
                                <div class="btn-group btn-group" style="font: 16px Helvetica Neue,Helvetica,Arial,sans-serif;">
                                    <input type="radio" id="mcap" href="#" name="mcap" value="29868" class="btn btn-outline-info waves-effect">Small Cap</input>
                                    <input type="radio" id="mcap" href="#" name="mcap" value="59736" class="btn btn-outline-info waves-effect">Mid Cap</input>
                                    <input type="radio" id="mcap" href="#" name="mcap" value="89604" class="btn btn-outline-info waves-effect">Large Cap</input>
                                    <input type="radio" id="mcap" href="#" name="mcap" value="119472" class="btn btn-outline-info waves-effect">Mega Cap</input>
                                </div>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-2">
                              <h2 style="font: 16px Helvetica Neue,Helvetica,Arial,sans-serif; margin: 0.5em;">   Sectors:   </h2>
                            </div>
                            <!--change the dropdown from bootstrap to normal select options-->
                            <!-- removed healthcare from the option-->
                            <div class="col-6">
                                <div class="dropdown">
                                    <select name="cat">
                                        <option name="cat" value="Basic"> Basic Materials </option>
                                        <option name="cat" value="Consumer"> Consumer Goods </option>
                                        <option name="cat" value="Serv"> Services </option>
                                        <option name="cat" value="Technology"> Technology </option>
                                        <option name="cat" value="Finance"> Financial </option>
                                        <option name="cat" value="Hotels"> Hotels </option>
                                        <option name="cat" value="Ind"> Industrial Goods </option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-2">
                              <h2 style="font: 16px Helvetica Neue,Helvetica,Arial,sans-serif; margin: 0.5em;">Share price: </h2>
                            </div>
                            <div class="col-6">
                                <div class="dropdown">
                                  <button class="btn btn-info dropdown-toggle btn-outline-info waves-effect" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    All
                                  </button>

                                  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                    <a class="dropdown-item" href="#">Up To RM1</a>
                                    <a class="dropdown-item" href="#">Above RM1</a>
                                  </div>
                                </div>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-2">
                              <h2 style="font: 16px Helvetica Neue,Helvetica,Arial,sans-serif; margin: 0.5em;">P/E: </h2>
                            </div>

                            <div class="col-6">
                                <div class="dropdown">
                                    <button class="btn btn-secondary dropdown-toggle btn-outline-info waves-effect" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    All
                                    </button>

                                    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                        <a class="dropdown-item" href="#">Below 10</a>
                                        <a class="dropdown-item" href="#">10-15</a>
                                        <a class="dropdown-item" href="#">16-25</a>
                                        <a class="dropdown-item" href="#">Above 25</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-2" >
                              <h2 style="font: 16px Helvetica Neue,Helvetica,Arial,sans-serif; margin: 0.5em;">P/B Value: </h2>
                            </div>

                            <div class="col-6">
                                <div class="dropdown">
                                    <button class="btn btn-secondary dropdown-toggle btn-outline-info waves-effect" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    All
                                    </button>

                                    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                        <a class="dropdown-item" href="#">Up to 0.5</a>
                                        <a class="dropdown-item" href="#">Up to 1.0</a>
                                        <a class="dropdown-item" href="#">Up to 2.0</a>
                                        <a class="dropdown-item" href="#">Above 2.0</a>
                                    </div>
                                </div>
                            </div>
                        </div>

                            <div class="row">
                                <div class="form-group">
                                {% csrf_token %}
                                    <button type="submit" class="btn btn-outline-info waves-effect">
                                        Filter Stocks
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form><!-- end of formquery-->
                    <br>
                    <br>

                    <div class="row">
                        <div class="col-sm">
                            <div class="container">

                                <table id="datatable" class="table table-hover">
                                    <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>ID</th>
                                        <th>Price</th>
                                        <th>Volume</th>
                                        <th>EPS</th>
                                        <th>DPS</th>
                                        <th>NTA</th>
                                        <th>PE</th>
                                        <th>DY</th>
                                        <th>ROE</th>
                                        <th>PTBV</th>
                                        <th>M.Cap</th>
                                    </tr>
                                    <tbody>
                                        {% for v in data%}
                                        <tr>
                                            <td>{{v.company_name}}</td>
                                        </tr>
                                        {% endfor %}
                                    </tbody>
                                    </thead>
                                    <tfoot>
                                    <tr>

                                    </tr>
                                    </tfoot>
                                </table>


                                <script>
                                        $(document).ready(function() {
                                        $('#datatable').DataTable({ data: "{{data}}" });;
                                     } );






                                </script>               

                  </div>
                </div>
              </div>
            </div>      


        </div>



{% endblock %}  

UPDATE:解决

在我的html中的数据表中我做了这个

$(document).ready(function() {
                                        var json = JSON.stringify({{data | safe}});
                                        $('#datatable').DataTable({ 
                                            "data": JSON.parse(json), 
                                             "columns": [
                                                     { "data": "company_name" },
                                                     { "data": "company_id" },
                                                     {"data": "company_categories"},
                                                     { "data": "companyprice" },
                                                     { "data": "companyvolume" },
                                                     { "data": "companyeps" },
                                                     { "data": "companydps" },
                                                     { "data": "companynta" },
                                                     { "data": "companype" },
                                                     { "data": "companydy" },
                                                     { "data": "companyroe" },
                                                     { "data": "companyptbv" },
                                                     { "data": "companymcap" }
                                                 ]
                                        });;
                                     } );

在我的views.py中我做了这个

views.py

stocks =  StockInfo.objects.filter(Q(company__company_categories__contains=sector),Q(companyprice__range=(startPriceRange,endPriceRange)),Q(companymcap__range=(startRange,endRange)),Q(datetimecollect__contains=datetime.date(2018,3,13)))
    serializer = TableSerializer(stocks,many=True)
    #qs = serializers.serialize('json',stocks)
    testing = json.dumps(list(serializer.data))
    context = {'data':testing,}
return render(request,'mypage.html',context)

1 个答案:

答案 0 :(得分:0)

您未在视图中指定任何template_name,并且您将APIView作为子类,因此将您带到该页面(图片)是正常的。

在主页模板或drf render中使用django HTMLRenderer功能:

from rest_framework.renderers import TemplateHTMLRenderer
class TableData(APIView):
    def post(self,request,*args,**kwargs):
        startRange = request.POST.get('mcap')
        endRange = int(startRange) + 29868
        sector = request.POST['cat']
        print(str(sector))
        ...
        serializer = TableSerializer(stocks,many=True)
        renderer_classes = [TemplateHTMLRenderer]
        template_name = 'homepage.html'
        return Response({'data': serializer.data})

data是您在首页模板中使用的变量,可以使用serializer.data