python - 除了粘贴新网址之外,还有更好的方法在 Django 的视图之间移动吗?
问题描述
我正在学习使用 Django 来构建我的 Web 应用程序。我想通过索引页面上的链接访问另一个页面,但浏览器不断将文件和应用程序名称附加到请求中。如何让浏览器切换链接而不每次都附加目录名称?
我已经尝试将 reg exp 与旧的 url 方法一起使用,但它似乎不起作用
# My project
# urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('index.urls')),
]
# My app
# urls.py
urlpatterns = [
path('index/',include([
path('', views.index,name="index"),
path('theteam', views.theteam,name="theteam"),
path('services',views.services,name="services"),
path('quotes',views.quotes,name="quotes"),
path('insurance',views.insurance,name="insurance"),
path('contact',views.contact,name="contact"),
path('thanks', views.thanks,name="thanks"),
])),
]
# Views
def index(request):
return render(request, 'index/index.html')
def theteam(request):
return render(request, 'index/theteam.html')
def services(request):
return render(request, 'index/services.html')
def quotes(request):
form = ContactForm(request.POST or None)
if request.method == 'POST':
return redirect(request, '/thanks/')
return render(request, 'index/quotes.html', { 'form': form })
def insurance(request):
return render(request, 'index/insurance.html')
def contact(request):
return render(request, 'index/contact.html')
def thanks(request):
return render(request, '/thanks.html')
#My Views HTML
<div class="menu-bar ">
<ul>
<a href="{% url 'services' %}"> <li>Services</li></a>
<a href="{% url 'theteam' %}"><li>The Team</li> </a>
<a href="{% url 'quotes' %}"><li>Quotes</li> </a>
<a href="{% url 'insurance' %}"> <li>Insurance</li></a>
<a href="{% url 'contact' %}"><li>Contact Us</li></a>
</ul>
</div>
到目前为止,我已经能够通过简单地将“/index/template/”粘贴到浏览器中来访问每个页面,但我无法在使用链接之间切换。我的预期结果是能够使用链接在页面之间切换。
解决方案
在您的应用程序 urls.py 中,在 urlpatterns 上方添加一行,如下所示:
app_name = your_app_name
然后,在您的 html 文件中,更改
{% url 'services' %}
至
{% url 'your_app_name:services' %}
推荐阅读
- c# - .Net Core ActionResult
总是返回假? - excel - 处理自写类的对象的默认属性在 64 位办公室中表现出奇怪的行为
- mongodb - 是否可以在自制软件的名称参考中创建快捷方式?
- c - seq_file 的迭代是否有任何限制
- html - CSS样式在不同大小的窗口中不对称
- django - 为什么我可以在 Python shell 中使用请求,但我得到错误 no module found in Django?
- django - django-elasticsearch-dsl 完成映射建议字段不起作用
- jenkins-pipeline - Jenkins 声明式管道中的并行项
- excel - Excel - 获取在另一列中找到匹配的行中的列的值
- javascript - 重定向到节点模板