【问题标题】:$.get() request not working with Django$.get() 请求不适用于 Django
【发布时间】:2016-01-12 21:35:10
【问题描述】:

我的 $.get() 请求似乎没有影响我的 Django 项目。

例如,当您手动将 URL 更改为 ?row=0&day=4 时,它可以正常工作,但在调用 Javascript 函数 index(x) 时,它就不起作用了。

我已经检查并且在打印 context['entry_form'] 生成正确的 html 时逻辑工作正常。

我不确定我是否正确使用了 Javascript $get() 调用?

Javascript:

function index(x) {
    theCellIndex = parseInt(x.cellIndex) - 2;
    theRowIndex = parseInt(x.parentNode.rowIndex) - 1;
    $.get( "{{ request.path }}", { 'row': theRowIndex, 'day': theCellIndex} );

}

姜戈:

if "day" and "row" in request.GET:
    day = request.GET.get("day")
    rownum = request.GET.get("row")
    allrows = RowControl.objects.filter(month_control_record=month_control_record)
    row = allrows[int(rownum)]
    selected_date = datetime.date(int(year), int(month), int(day))

    try:
        form_instance = Entry.objects.get(row_control=row, date=selected_date)
        entry_form = EntryForm(instance=form_instance)
    except Entry.DoesNotExist:
        entry_form = EntryForm(initial={'row_control': row, 'date': selected_date})

context = {
    'entry_form': entry_form,
}

print(context['entry_form'])

return render(request, "timesheet/monthview.html", context)

编辑: 目标是让这个模板代码正确更新:

    <form method="POST" action="{{ request.path }}">
    {% csrf_token %}
        {{ entry_form|crispy }}
        <button class="btn btn-primary" type="submit" value="Submit" name="entry_submit" ><i class="fa fa-lg fa-floppy-o"></i> Save</button>
    </form>

【问题讨论】:

  • 不要使用{{ request.path }},您的设置中可能有也可能没有'django.core.context_processors.request'。请改用{% url %} 模板标签。
  • 好的,我已经编辑了我的答案,如何让显示的模板数据更新?如何手动更改?

标签: javascript python django django-forms


【解决方案1】:
$.get( "{{ request.path }}", { 'row': theRowIndex, 'day': theCellIndex} );

您只是发出GET 请求,但没有对响应做任何事情。理想情况下,您可能希望将返回的 HTML 响应加载到某些 div 或其他内容。

代码应该有第三个参数,一个在响应返回时执行的回调函数。

 $.get( "{{ request.path }}", { 'row': theRowIndex, 'day': theCellIndex}, function(response) {
    console.log(response);
} );

【讨论】:

  • 我已经更新了我的问题。如何使用此响应来更改模板中的表单,有/无重新呈现页面?
  • 您想如何更新表单?你可以在回调中做任何你想做的事情。
  • 如何格式化响应以显示为 django 表单?代码:formattedresponse = {{ response|crispy }} 不返回任何内容。
  • 响应是 JS,所以 django 模板代码不起作用。你必须使用 JS 来做你想做的事。
猜你喜欢
  • 2019-04-11
  • 2014-07-12
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
  • 2020-11-25
  • 2020-07-19
  • 2020-07-07
  • 1970-01-01
相关资源
最近更新 更多