我正在学习Django,在我的应用中,我有一个urls.py,其中包含4个网址格式。如果url的末尾没有输入任何字符串,则必须按照代码将其重定向到索引页面,但不会发生。其余网址正常工作。
我的urls.py
from django.contrib import admin
from django.urls import path
from .views import index, about, news
from django.conf import settings
from mainsite import views
urlpatterns = [
path(r'^$', views.index, name='index'),
path(r'about/', views.about, name='about'),
path(r'news/', views.news, name='news'),
path(r'admin/', admin.site.urls),
]
我的views.py
from django.shortcuts import render
from datetime import datetime
from .models import Article
def index(request) :
context = {
'current_date': datetime.now(),
'title': 'Home'
}
return render(request, 'index.html', context )
def about(request) :
context = {
'current_date': datetime.now(),
'title': 'About'
}
return render(request, 'about.html', context )
def news(request) :
populate_db()
articles = get_articles()
context = {
'articles': articles,
'current_date': datetime.now(),
'title': 'News'
}
return render(request, 'news.html', context )
def get_articles():
result = Article.objects.all()
return result
def populate_db():
if Article.objects.count() == 0:
Article(title = 'first item', content = 'this is the first database item').save()
Article(title = 'second item', content = 'this is the second database item').save()
Article(title = 'third item', content = 'this is the third database item').save()
这是我遇到的错误 enter image description here
答案 0 :(得分:2)
从以下位置更改您的网址路径:
path(r'^$', views.index, name='index'),
到
path('', views.index, name='index'),
因为path将字符串或带有尖括号的部分(例如<username>
)用于url的动态部分。您的其他网址格式定义也是如此:
path('about/', views.about, name='about'),
path('news/', views.news, name='news'),
path('admin/', admin.site.urls),
如果您打算将正则表达式用作url模式的一部分,请使用re_path。
答案 1 :(得分:0)