python django如何在Post请求中向网站发送参数

时间:2018-05-23 16:16:39

标签: python css django

我正在使用python Django构建一个网站。我想做以下项目。

首先,我从网站上获取输入值。然后我使用输入值生成绘图并将其保存在服务器的一个位置。之后,我想将剧情的位置发回网站。

我的代码如下:

在views.py

来自django.shortcuts导入渲染 import trip.forms

#First define to Django form.Forms
    form_class = trip.forms.AdHocTripReportRequestForm   
    graphurl_form=trip.forms.Graphurl

    #Then define a "get" function
        def get(self, request):
            encoded_cabinets, id_dirserved = self._encoded_page_precache()
            ctx = {
               'CABINETS': encoded_cabinets,
                'ID_DIRSERVED': id_dirserved,
                'form': self.form_class(),
                'graph': self.graphurl_form(),
              }
             # add adhoc settings
             profile = get_profile(request.user)
             if profile:
                 ctx.update(defaults=profile.get_settings('adhoctrip'))
             context = RequestContext(request, ctx)
             return render_to_response("adhoc-trip.html", context)


    #after that, there is a post function
         def post(self, request):
              #1) read the input values
             form = self.form_class(request.POST)
             if form.is_valid(request.user):
                 # update adhoc settings
                 profile = get_profile(request.user)
                 if profile:
                     settings_form = DateRangeDowEmailForm(request.POST)
                     if settings_form.is_valid():
                         profile.set_settings('adhoctrip', settings_form.cleaned_data)
                         profile.save()

                 # 2) some functions to get the link string
                     graphurl=trip.tasks.TripReportTask().delay(trr, recipients, server, save_as, trr1)

                 # 3) set this information to the html file
                     graphurl_form_tmp=trip.forms.Graphurl(request.POST or 
                                None, initial={'name': graphurl})
                     return render(request, "adhoc-trip.html", 
                                {'graph' : graphurl_form_tmp,})

在adhop-trip.html中

    <script type="text/javascript">
    var TripButtonBase = Backbone.Model.extend({
        initialize: function(options) {
            options = options || {};
            this.waypoints = options.waypoints;
            this.dateInput = options.dateInput;
            this.corridorType = options.corridorType;
            this.compareYear=options.compareYear;
            this.errorList = options.errorList;
            this.omitList = options.omitList;
        },
        params: function() {
            // short-term fix to "is endpoint unchecked?" while new trip interface is completed
            try {
                var omittedLoopgroupIds = this.omitList.getOmitList();
            } catch(err) {
                alert("I'm sorry, but both trip endpoints must be checked in the Route Editor/Data Quality tab or no travel times can be calculated.
                return;
            }
            // end fix

            return _.extend(this.waypoints.params(), this.dateInput.params(),
                {omittedLoopgroupIds: omittedLoopgroupIds, corridorType: this.corridorType.val(), compareYear: this.compareYear.val()});
        }
    });

    var EmailTripButton = TripButtonBase.extend({
    // Request an adhoc trip report
    post: function() {
        var data = this.params();
        data.recipientEmail = $('#recipientEmail').val();
        var url = siteUrl('trip/adhoc-trip/');

        $.ajax(url, {
            context: this,
            data: data,
            dataType: "json",
            traditional: true, // serialize nested arrays with identical keys e.g., b=1&b=2&b=3
            type: "POST",
            success: this.postSuccess,
            error: this.postError,
        });
    },
    postSuccess: function(data, textStatus, jqXHR) {
        alert("Trip will be emailed to you shortly");
        this.errorList.reset();
    },
    postError: function(jqXHR, textStatus) {
        switch (jqXHR.statusText) {
        case "BAD REQUEST":
            var errInfo = $.parseJSON(jqXHR.responseText);
            this.errorList.reset(errorInfoToErrors(errInfo));
            break;
        default:
            alert("Error in submitting trip");
            console.log(jqXHR);
            console.log(textStatus);
            break;
        }
    },
});
{% endblock script %}

一旦我在views.py中添加最后一行(返回渲染...),系统将触发postError函数,而不是postSuccess函数。

非常欢迎任何赞扬和建议。

1 个答案:

答案 0 :(得分:1)

请始终包含完整堆栈跟踪。它可以更容易地确定实际错误。

没有它我只能猜测。想到的一些想法:

  1. 最后一条评论后代码的缩进似乎已关闭。如果它与实际文件中的相似,则可能是错误
  2. 确保导入程序正在使用的所有内容。例如,确保 '来自django.shortcuts导入渲染' 在您的档案中的某处。