【发布时间】:2019-06-05 00:06:57
【问题描述】:
我想重复使用相同的模板“createchapter.html”。 换句话说,我想链接到“createchapter/?step=1.html”、“createchapter/?step=2.html”、“createchapter/?step=3.html”。
我使用的是 Django 2.1.5,所以学习的资源或问答很少。
在 urls.py 中
urlpatterns = [
(.....)
url(r'^createbook/$',viewsSentence.createbook),
url(r'^createchapter/<int:step>$',viewsSentence.createchapter),
]
在views.py中
@csrf_exempt
@csrf_protect
def createchapter(request,path):
if request is not None:
if request.GET.get('step') is None:
context1 = {
'books': book.objects.order_by('titleOrigin'),
'step': 1,
}
#useless: return HttpResponse('/?step=1',context1)
redirect("createchapter.html",context1,step=1)
elif request.GET.get('step') == 2:
context2 = {
'step': 2,
}
redirect("createchapter.html", context2,step=2)
在 createchapter.html 中
{% if step == 1 %}
<form>
{% csrf_token %}
<div class="form-group">
<i class="fas fa-forward"></i>
<label for="select-books">Step 1: select a book</label>
<select class="form-control" id="select-books">
{% for book in books %}
<option value="{{ book.id }}">{{ book.titleOrigin }}</option>
{% endfor %}
</select>
</div>
</form>
<div class="d-flex justify-content-center">
<i class="fas fa-arrow-alt-circle-right"><a id="createchapter-step2">Step 2</a></i>
</div>
{% elif step == 2%}
<div class="form-group">
<i class="fas fa-forward"></i>
<label>Step 2: set numbers of chapters</label>
</div>
{% endif %}
这是我如何调用第二页(我使用 ajax):
$("#createchapter-step2").click(function(){
var selectedbookId = $("#select-books option:selected").val();
$.ajax({
url: '/createchapter/?step=2',
type:'get',
data:{
'selectedbookId':selectedbookId,
csrfmiddlewaretoken: $( "#csrfmiddlewaretoken" ).val(),
},
});
});
错误信息是:
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/createchapter/?step=1/
【问题讨论】:
-
step=1 无法按照您的代码工作。但只需将其保留为127.0.0.1:8000/createchapter/1
-
@VineethSai,我也试过 JPG 的方法。谢谢你。在我的 urls.py 中,我写了“^createchapter/
/$”,错误消息是“当前路径 createchapter/1/,与这些都不匹配。”。调试说我的请求 URL 是 127.0.0.1:8000/createchapter/1 。
标签: python django url redirect