【发布时间】:2026-01-06 21:15:01
【问题描述】:
我正在尝试在 django 中加载一个已存在于数据库中的 pdf 文件。 我可以使用 url 访问 pdf 文件,“localhost:8000/documents/file.pdf” 但是当我执行查询并返回包含此文件的响应时,它会重定向到不存在的“localhost:8000/ans/documents/file.pdf”。 html代码为:
<form id="signup-form" method="POST" action="ans/">
{% csrf_token %}
<input type="text" name="id" id="id" placeholder="Report id" />
<input type="submit" value="Check" />
</form>
urls.py中的路径是
path('ans/',views.func),
观点是:
def func(request):
if request.method=="POST":
id=request.POST.get("id")
ans = query.objects.get(id=id)
response=ans.repo
if ans is None:
return render(request,"index.html",{})
else:
return redirect(response)
底线是,我不想去掉 url 中的“/ans/”。
【问题讨论】:
-
尝试从表单中删除
action属性并提供反馈。 -
@MiniGunnR 如果我这样做,那么我将如何将请求传递给视图?
-
创建一个可以唯一呈现此 pdf 的不同视图,在 urls.py 中使用它自己的
path定义它,然后使用HttpResponseRedirect('that_new_path') -
我不明白你想在你的视图中做什么。你想在某处显示文件还是让别人下载它?
-
@TahseenRahman 在 Django 中使用 if else 来编写显示表单的视图有一定的方法。这不像你以前在 PHP 中所做的那样。我已经看到
action属性可以在 Django 表单中跳过。请阅读 django 文档中的Forms。
标签: python django python-3.x django-2.1