Skip to content

Commit

Permalink
Added SEO-friendly URLs for posts
Browse files Browse the repository at this point in the history
  • Loading branch information
yahyaaly151989 committed Aug 20, 2023
1 parent fa70c44 commit 43b4d5f
Show file tree
Hide file tree
Showing 9 changed files with 33 additions and 5 deletions.
Binary file modified Module02/mysite/blog/__pycache__/models.cpython-311.pyc
Binary file not shown.
Binary file modified Module02/mysite/blog/__pycache__/urls.cpython-311.pyc
Binary file not shown.
Binary file modified Module02/mysite/blog/__pycache__/views.cpython-311.pyc
Binary file not shown.
18 changes: 18 additions & 0 deletions Module02/mysite/blog/migrations/0002_alter_post_slug.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.2.4 on 2023-08-20 11:59

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('blog', '0001_initial'),
]

operations = [
migrations.AlterField(
model_name='post',
name='slug',
field=models.SlugField(max_length=250, unique_for_date='publish'),
),
]
Binary file not shown.
7 changes: 5 additions & 2 deletions Module02/mysite/blog/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class Status(models.TextChoices):
PUBLISHED = 'PB', 'Published'

title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
Expand All @@ -29,6 +29,9 @@ def __str__(self):

def get_absolute_url(self):
return reverse("blog:post_detail", args=[
self.id
self.publish.year,
self.publish.month,
self.publish.day,
self.slug,
])

2 changes: 1 addition & 1 deletion Module02/mysite/blog/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@

urlpatterns = [
path('', views.post_list, name='post_list'),
path('<int:id>/', views.post_detail, name='post_detail'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'),
]
11 changes: 9 additions & 2 deletions Module02/mysite/blog/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ def post_list(request):
posts = Post.objects.all()
return render(request, 'blog/post/list.html', {'posts': posts})

def post_detail(request, id):
post = get_object_or_404(Post, id=id, status=Post.Status.PUBLISHED)
def post_detail(request, year, month, day, post):
post = get_object_or_404(
Post,
status=Post.Status.PUBLISHED,
slug=post,
publish__year=year,
publish__month=month,
publish__day=day
)
return render(request, 'blog/post/detail.html', {'post': post})
Binary file modified Module02/mysite/db.sqlite3
Binary file not shown.

0 comments on commit 43b4d5f

Please sign in to comment.