Django-为什么在使用ajax之后,它变成了一个空页面

时间:2015-10-23 06:20:08

标签: python ajax django

页面上的功能:

  • 用户在表单上输入一些信息
  • 没有刷新,右侧可以根据用户输入显示一些查询结果(销售)

在添加ajax功能之前,页面可以显示表单和表格。但是在使用ajax之后,页面变空了。

任何人都可以帮忙查看是什么原因?提前谢谢。

网址

url(r'^result_list/$',ResultView.as_view(),name='result'),

models.py

class Input(models.Model):
    company=models.CharField(max_length=100)
    region=models.CharField(max_length=100)   

class Result(models.Model):
    sales=models.IntegerField(blank=False,null=False)

views.py

从django.views.generic.list导入ListView 来自django.core导入序列化程序

class ResultView(ListView):
    context_object_name = 'result_list'
    template_name = 'result_list.html'

    def get_queryset(self):
        return Result.objects.all()

    def post(self, request, *args, **kwargs):
        form = InputForm(request.POST)
        if form.is_valid():
            if self.request.is_ajax():
                company = form.cleaned_data['company']
                region = form.cleaned_data['region']

                queryset=Result.objects.filter(region=region).aggregate(Sum('sales'))
                return HttpResponse(json.dumps(queryset))

        else:
             return HttpResponse(form.errors)

    '''def get_context_data(self, **kwargs):
        context = super(ResultView, self).get_context_data(**kwargs)
        context["sales"] = self.get_queryset().aggregate(Sum('sales'))'''

HTML

<style>...CSS part
</style>

<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#InputForm").submit(function() { // catch the form's submit event
    var region= $("#id_region").val();
    var company= $("#id_company").val();

        $.ajax({
        data: $(this).serialize(), // get the form data
        type: $(this).attr('post'),
        dataType: 'json',
        url: "dupont_list/",
        success: function(data) {
        var html = "<table>"
        html += "<td>"+data['sales__sum']+"</td>"
        html += "</table>"
        $("#result").html(html);

            html += "</table>"
            $("#result").html(html);
        }   
        return false;
    });
})
</script>

<form id="InputForm" method="post" action="">   #here is the data entry form
        {% csrf_token %}

        <!--enter the company name--> 
        <div class="field">
            {{ form.company.errors }}
            <label id="id_company" name="company" for="{{ form.company.id_for_label }}">Company:</label>
            {{ form.company }}
        </div>

        <!--select region-->
        <div class="field" >
            <label> Select the Region:
            {{ form.region }}
                {% for region in form.region.choices %}
                     <option value="region" name= "region" id="id_region">{{region}} </option>
                {% endfor %}
            </label>
        </div>

        <!--submit-->
        <p><input type="button" value="Submit" /></p></div>
    </form> 
</div>

    <div id="result" class="result">   <!--Showing the filtered result in database-->
    <table>
    <tr><b>Sales</b></tr>
    <td> {{sales.sales__sum}}</td>

    <tr><b>Employee</b></tr>
    <td> {{employee.employee__sum}}</td>
    </table>

1 个答案:

答案 0 :(得分:1)

我会选择FormView

class ResultView(FormView):

    context_object_name = 'result_list'
    template_name = 'result_list.html'
    form_class = InputForm

    def get_context_data(self, **kwargs):
        context = super(ResultView, self).get_context_data(**kwargs)
        context["results"] = Result.objects.all()
        context["sales"] = context.results.aggregate(Sum('sales'))
        return context

    def form_valid(self,form):
        company = form.cleaned_data['company']
        region = form.cleaned_data['region']
        queryset = Result.objects.filter(region=region).aggregate(Sum('sales'))
        return HttpResponse(json.dumps(queryset))

这样,如果表单有效,您就会绕过get_context_dataget_queryset方法,并返回自定义内容回复。