我有一个用Django构建的基本应用程序,只有在我输入时才有效:
http://xx.xx.xxx.xx/polls
。如何在 urls.py 文件中重写此内容,以便http://xx.xx.xxx.xx/polls
将我重定向到http://xx.xx.xxx.xx/
?
主要项目的 urls.py 文件:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
]
应用程序中的 urls.py 文件:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
]
我的项目结构:
├── blog
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── settings.py
│ ├── settings.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── wsgi.py
│ └── wsgi.pyc
├── db.sqlite3
├── manage.py
├── polls
│ ├── admin.py
│ ├── admin.pyc
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── 0001_initial.pyc
│ │ ├── __init__.py
│ │ └── __init__.pyc
│ ├── models.py
│ ├── models.pyc
│ ├── templates
│ │ └── polls
│ │ ├── detail.html
│ │ ├── index.html
│ │ ├── results.html
│ │ └── static
│ │ └── polls
│ │ ├── css
│ │ │ ├── semantic.css
│ │ │ ├── semantic.min.css
│ │ │ ├── sidebar.css
│ │ │ ├── sidebar.min.css
│ │ │ ├── sidebar.min.js
│ │ │ └── style.css
│ │ ├── images
│ │ └── js
│ │ ├── jquery-1.11.2.min.js
│ │ ├── semantic.js
│ │ ├── semantic.min.js
│ │ ├── sidebar.js
│ │ └── sidebar.min.js
│ ├── tests.py
│ ├── tests.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ └── views.pyc
├── readme.txt
├── requirements.txt
├── templates
│ └── admin
│ └── base_site.html
答案 0 :(得分:3)
据我所知,你不是要从/polls/
重定向到/
,而是想在主页上显示民意调查索引。如果是,那么只需将index
网址从polls/urls.py
移至主urls.py
:
from polls.views import IndexView
urlpatterns = [
url(r'^$', IndexView.as_view(), name='index'),
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
]
更新:在django模板/代码中使用硬编码的网址是一种不好的做法。您应始终使用{% url %}
模板标记和reverse()
功能。这样您就可以根据需要更改网址而不会破坏代码。
所以索引页面的链接应该是这样的:
<a href="{% url 'index' %}">Home page</a>
例如,链接到投票详情:
<a href="{% url 'polls:detail' poll.pk %}">Poll #{{ poll.pk }}</a>
在模型的get_absolute_url()
方法中,使用reverse()
。
答案 1 :(得分:1)
您还可以将整个民意调查应用包含在&#39; /&#39;通过做:
url(r'^', include('polls.urls', namespace="polls")),
另外,请参阅此处以获取有关在urls.py中重定向的更多信息: Redirect to named url pattern directly from urls.py in django?
在你的情况下,它会是这样的:
from django.views.generic import RedirectView
url(r'^polls/', RedirectView.as_view(pattern_name='polls:index')