将数据从日期选择器表单传递到APIView

时间:2018-12-11 17:38:15

标签: django view django-rest-framework jquery-ui-datepicker

我目前正在尝试使用graphjs在我的网站上动态加载图形。我要做的是通过选择时间范围或特定的数据类型来更新数据。我希望它更加灵活,并且只有两种观点。一种用于渲染图形,另一种用于返回相关数据。 我认为我的日期小部件将使用post方法通过HomeView传递数据。如何将日期信息传递给GenericDataView?也许还有另一种方式可以做这种事情。

编辑

class HomeView(View):
    def get(self,request,*args,**kwargs):
        return render(request,'charts/charts.html')

class GenericDataView(APIView):
    def get(self,request,*args,**kwargs):
        selected_data = getDataFromTimeRange()

        if selected_data is not None:
             return Response(selected_data)

        if request.method == 'POST':
            form = DatePickerCustom(request.POST)
            if form.is_valid():
                mydate = form.cleaned_data('production_day')
                print("DATE: ", mydate)
        else:
            form = DatePickerCustom()

def getDataFromTimeRange():
     // do things
     return data;

在Forms.py中:

dateCustomInput = DateInput(attrs={'class':'datepicker'})

class DatePickerCustom(Form):
    production_day = DateField(label='Production day',widget=dateCustomInput)

然后在chart.hmtl中:

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            console.log(xhr)
            console.log(csrftoken)
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
            console.log(X-CSRFToken)
        }
    }
});
<div class="chart-container"  url-endpoint='{% url "api-data" %}' style="position: relative">
        <canvas id="myChart"></canvas>
</div>
<form action="chart" method="post" enctype='multipart/form-data'>
    <!-- {{ csrf_input }}-->
    {% csrf_token %} 
    <label for="date">Choose a date: </label>
    <input id="datepicker" type="text" name="selectedDate" value="{{ form }}">
    <input type="submit" value="OK">
</form>

0 个答案:

没有答案