Skip to content

Commit

Permalink
change url routes to remove pk
Browse files Browse the repository at this point in the history
  • Loading branch information
Joe Kaufeld committed Jun 15, 2021
1 parent 21874fd commit e72a7f8
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 6 deletions.
2 changes: 1 addition & 1 deletion website/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class Post(models.Model):

def get_absolute_url(self) -> str:
"""Return the full url of a given post."""
kwargs = {"pk": self.id, "slug": self.slug}
kwargs = {"slug": self.slug}
return reverse("post_detail", kwargs=kwargs)

def save(self, *args: object, **kwargs: object) -> None:
Expand Down
11 changes: 9 additions & 2 deletions website/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@

urlpatterns = [
path("", views.index, name="homepage"),
path("posts/<int:pk>-<str:slug>/", views.PostDetail.as_view(), name="post_detail"),
# compatibility layer to allow old style URLs to resolve to slug-only.
# Must be above regular version.
path(
"posts/<int:pk>-<str:slug>/",
views.post_view_redirect,
name="post_detail_redirect",
),
path("posts/<str:slug>/", views.PostDetail.as_view(), name="post_detail"),
path(
"newpost", grafeas_staff_required(views.PostAdd.as_view()), name="post_create"
),
path(
"posts/<int:pk>-<str:slug>/edit/",
"posts/<str:slug>/edit/",
grafeas_staff_required(views.PostUpdate.as_view()),
name="post_update",
),
Expand Down
9 changes: 6 additions & 3 deletions website/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpRequest, HttpResponse
from django.shortcuts import HttpResponseRedirect, redirect, render
from django.shortcuts import HttpResponseRedirect, redirect, render, reverse
from django.views.generic import DetailView, TemplateView, UpdateView

from authentication.mixins import GrafeasStaffRequired
Expand All @@ -29,7 +29,6 @@ class PostDetail(DetailView):
"""Render a specific post on the website."""

model = Post
query_pk_and_slug = True
template_name = "website/post_detail.html"

def get_context_data(self, **kwargs: object) -> Dict:
Expand All @@ -39,11 +38,15 @@ def get_context_data(self, **kwargs: object) -> Dict:
return context


def post_view_redirect(request: HttpRequest, pk: int, slug: str) -> HttpResponse:
"""Compatibility layer to take in old-style PK+slug urls and return slug only."""
return HttpResponseRedirect(reverse("post_detail", kwargs={"slug": slug}))


class PostUpdate(GrafeasStaffRequired, UpdateView):
"""Modify a post on the website."""

model = Post
query_pk_and_slug = True
fields = [
"title",
"body",
Expand Down

0 comments on commit e72a7f8

Please sign in to comment.