Changing from int:pk to Slug

Submitted 1 year, 12 months ago
Ticket #6
Views 171
Language Django
Priority Low
Status Closed

I am trying to switch from writing the id:pk of the blog to writing a function to add the post title to become a slug.

So I am currently trying to switch all my post details to slug but after I finished everything I am getting a page error 404 which doesn't indicate exactly where I have something wrong with my code.

My question is when I move from changing the URLs from int:id to slug what should I be looking for to change as well to avoid page error 404?

In the URL for every page detail, I am getting the int:id not the title of the post and the error 404

I am doubting the get_absolute_url

I have commented the addition of the slug function: Here is the models.py :

class Post(models.Model):
    designer = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    likes = models.ManyToManyField(
        User, related_name='liked')
    slug = models.SlugField(blank=True, null=True, max_length=120)

     def save(self, *args, **kwargs):
         if not self.slug:
             self.slug = slugify(self.title)
         super(Post, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse("score:post-detail", kwargs={'slug': self.slug})

Here is the views.py

class PostDetailView(DetailView):
    model = Post
    template_name = "post_detail.html"

    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data()
        stuff = get_object_or_404(Post, id=self.kwargs['slug'])
        total_likes = stuff.total_likes()
        liked = False
        if stuff.likes.filter(id=self.request.user.id).exists():
            liked = True
        context["total_likes"] = total_likes
        context["liked"] = liked
        return context


def LikeView(request):
    post = get_object_or_404(Post, id=request.POST.get('id'))
    liked = False
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
        liked = False
    else:
        post.likes.add(request.user)
        liked = True

    context = {
        'total_likes': post.total_likes,
        'liked': liked,
        'post': post
    }

    if request.is_ajax:
        html = render_to_string('like_section.html', context, request=request)
        return JsonResponse({'form': html})

here is the url

urlpatterns = [
    path('', PostListView.as_view(), name='score'),
    path('<slug:slug>/', PostDetailView.as_view(), name='post-detail'),
    path('new/', PostCreateView.as_view(), name='post-create'),
    path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
    path('<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'),
    path('<slug:slug>/delete/', PostDeleteView.as_view(), name='post-delete')
Submitted on May 22, 20
add a comment

2 Answers

Verified

Assigned to our Techie Developer

Submitted 1 year, 12 months ago

your `get_absolute_url' setup is wrong, PFB the sample ,

Step 1: def get_absolute_url(self): return reverse("app_name:detail", kwargs={"slug": self.slug}) Step 2: In URL.py app_name = 'blogs' path('blog/<slug:slug>/', view.detail,name='detail'), Steps 3: We should have view for this.

- bookletgo 1 year, 12 months ago

the view is written in the question

- ahmed.hisham87 1 year, 12 months ago

yes i know.. what i am saying is problem in URL & get_absolute_url method. If you see the sample which i sent you could understand better

- bookletgo 1 year, 12 months ago

``` class PostDetailView(DetailView): model = Post template_name = "post_detail.html"

def get_context_data(self, *args, **kwargs):
    context = super(PostDetailView, self).get_context_data()
    stuff = get_object_or_404(Post, id=self.kwargs['pk']) <--- Error from here
    total_likes = stuff.total_likes()
    liked = False
    if stuff.likes.filter(id=self.request.user.id).exists():
        liked = True
    context["total_likes"] = total_likes
    context["liked"] = liked
    return context

```

- ahmed.hisham87 1 year, 12 months ago

add app_name in ur url and use that app_name in get_aboslute_url method like this return reverse(appname:details, kwargs={'slug': self.slug}

- arun 1 year, 12 months ago

it is a PostDetailView(DetailView) not just a view

- ahmed.hisham87 1 year, 12 months ago

yes CBC or generic view doesnt matter. you need to point the name in URL,

path('blog/<slug:slug>/', BlogDetailView.as_view(),name='detail'), . like this

- arun 1 year, 12 months ago

Is it working?

- arun 1 year, 12 months ago

no it didn't

- ahmed.hisham87 1 year, 12 months ago

we have already shared the code. you just need to replace with your app name & view name.. thats it

- arun 1 year, 12 months ago

Ok just bare with here are the final amendments I made and if there is anything wrong please inform me in the urls path('<slug:slug>/', PostDetailView.as_view(), name='post-detail'), in the models def get_absolute_url(self): return reverse("score:post-detail", kwargs={'slug': self.slug})

in the views.py ``` stuff = get_object_or_404(Post, id=self.kwargs['slug']) <--- Error shows from here

```

- ahmed.hisham87 1 year, 12 months ago

May be tomorrow we will setup the meeting to discuss on this

- arun 1 year, 12 months ago

can we connect at 12.30 PM PST via zoom?

- arun 1 year, 12 months ago

sorry I just saw your message? Yes we can meet in a zoom session when would be a good time for you

- ahmed.hisham87 1 year, 12 months ago

how about 6.30 PM PST?

- arun 1 year, 12 months ago

sure 6:30 pst

- ahmed.hisham87 1 year, 12 months ago

sent you the webex link

- arun 1 year, 12 months ago

can you join?

- arun 1 year, 12 months ago

Thank you so much

Submitted 1 year, 12 months ago

Welcome. As you can always support us Donate . If you want :)

- arun 1 year, 12 months ago

The problem is solved but can we join the call one more time quickly other pages need minor amendments such as create new, update and delete

- ahmed.hisham87 1 year, 12 months ago

as this ticket is already closed. Please submit new one.

- arun 1 year, 12 months ago


Wanna Post Ad?
Reach a large group of audience by posting an ad about your business here. For more details
Drop us a Message