0
votes

Sir, I'm developing a slug project in Django. When I try to print the slug id post it will not display shows 404 error. Tried n number of times. Anyone, please help me to fix this in urls.py.

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily Using the URLconf defined in postscommentpro.urls, Django tried these URL patterns, in this order:

admin/ postscommentapp/(?P\d+)/(?P[\w-]+)/$ [name='post_detail'] The current path, postscommentapp/6/how-learn-anything-very-easily, didn't match any of these.

models.py

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Post(models.Model):
    STATUS_CHOICES = (
            ('draft', 'draft'),
            ('published', 'published')
        )
    title = models.CharField(max_length=50)
    slug = models.CharField(max_length=50)
    author = models.ForeignKey(User, on_delete = models.CASCADE)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')

    def __str__(self):
        return self.title

admin.py

from django.contrib import admin
from .models import Post
# Register your models here.

class AdminPost(admin.ModelAdmin):
    list_display = ['title', 'slug', 'body', 'author', 'created', 'updated', 'status']
    prepopulated_fields = {'slug':('title',)}
    list_editable = ('status',)
admin.site.register(Post, AdminPost)

views.py

from django.shortcuts import render
from .models import Post
# Create your views here.

def post_List(request):
    posts = Post.objects.all()
    return render(request, 'postscommentapp/post_list.html', {'posts':posts})

def post_detail(request, id, slug):
    post = Post.objects.get(id=id)
    return render(request, 'postscommentapp/post_detail.html', {'post':post})

url.py - postscommentapp

from django.urls import path
from postscommentapp import views

urlpatterns = [
    path('', views.post_List, name=''),
    path('postscommentapp/(?P<id>\d+)/(?P<slug>[\w-]+)/$', views.post_detail, name='post_detail'),
]

urls.py

"""postscommentpro URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('postscommentapp.urls')),
]

post_detail.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<h2>{{ post.title }}</h2>
</body>
</html>

post_list.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <!-- Bootstrap CDN Lines -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@600;700&display=swap" rel="stylesheet">
</head>
<style>
    .col-md-6{
        text-align: justify;
    }
    .img-thumbnail{
        border:1px solid #6b6b47;
    }
    .title{
        font-family: 'Poppins', sans-serif;
    }
</style>
<body style="font-family: 'Poppins', sans-serif;">
<div class="container-fluid">
    <br>
    <h2 class="text-center" style="font-weight:bold; color: #0040ff;">Post Comments Python/Django Project:</h2>
    <div class="row">
        {% for each_item in posts %}
            <div class="col-md-6">
                <br>
                <div class="img-thumbnail">
                ⭐ <a href="#" class="title">{{ each_item.title }}</a><small style="float:right">{{ each_item.created }}</small><br>
                ➟ Author: {{ each_item.author }}<br><br>
                {{ each_item.body }}<br>
                </div>
                <br>
            </div>
        {% endfor %}
    </div>
</div>
</body>
</html>
1
Add a a slash` / at the end of the URL. - Willem Van Onsem
Tried / at end of URL. But, the slug id post page displayed not found. Again same error Page not found. @WillemVanOnsem sir. - Kartheek Ravula

1 Answers

0
votes

I solved this error in my own way. In urls.py postscommentapp

from django.urls import path
from postscommentapp import views

urlpatterns = [
    path('', views.post_List, name=''),
    path('postscommentapp/(?P<id>\d+)/(?P<slug>[\w-]+)/$', views.post_detail, name='post_detail'),
]

change this url code in to this urls.py - postscommentapp

 from django.urls import path
    from postscommentapp import views
    
    urlpatterns = [
        path('', views.post_List, name=''),
        path('post/<int:id>/<slug:slug>/', views.post_detail, name='post_detail'),
    ]

Write this line in views.py

from django.shortcuts import render, get_object_or_404
from .models import Post
# Create your views here.

def post_List(request):
    posts = Post.objects.all()
    return render(request, 'postscommentapp/post_list.html', {'posts':posts})

def post_detail(request, id, slug):
    # post = Post.objects.get(id=id)
    post = get_object_or_404(Post, id=id, slug=slug)
    return render(request, 'postscommentapp/post_detail.html', {'post':post})