NITISH KUMAR
NITISH KUMAR

Reputation: 59

Django- empty string in url is not redirecting to the index page

I'm learning django and in my app, I have a urls.py which has 4 url patterns in it. if there is no string entered in the end of url then it must redirect to the index page as per the code but it is not happening. Rest url are working fine.

MY 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),
]

My 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()

This is the error i'm getting enter image description here

Upvotes: 3

Views: 2848

Answers (2)

Sammy J
Sammy J

Reputation: 1066

According to the Django Docs you must not use regular expression in path(), check it here path if you want to use regular expression, then use re_path specified here re_path.

Upvotes: 1

ruddra
ruddra

Reputation: 51978

Change your url path from:

path(r'^$', views.index, name='index'),

to

path('', views.index, name='index'),

Because path takes string or parts with angle bracket like <username> for dynamic parts of url. Same goes to your other url pattern definitions:

path('about/', views.about, name='about'),
path('news/', views.news, name='news'),
path('admin/', admin.site.urls),

If you are planning to use regex as part of url patterns, then please use re_path.

Upvotes: 6

Related Questions