首页 > 解决方案 > 除了粘贴新网址之外,还有更好的方法在 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/”粘贴到浏览器中来访问每个页面,但我无法在使用链接之间切换。我的预期结果是能够使用链接在页面之间切换。

标签: pythondjangodjango-views

解决方案


在您的应用程序 urls.py 中,在 urlpatterns 上方添加一行,如下所示:

app_name = your_app_name

然后,在您的 html 文件中,更改

{% url 'services' %}

{% url 'your_app_name:services' %}

推荐阅读