url中的Django-空字符串不会重定向到索引页面

问题描述 投票:0回答:2

我正在学习django,在我的应用程序中,我有一个urls.py,里面有4个url模式。如果在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的错误

python html django django-views django-urls
2个回答
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),

如果您打算使用正则表达式作为网址模式的一部分,请使用re_path


0
投票

根据Django Docs你不能在path()中使用正则表达式,如果你想使用正则表达式,请在这里检查path,然后使用re_path指定的re_path。

© www.soinside.com 2019 - 2024. All rights reserved.