So I am trying to link up a page on my blog. I have created the template, view and URL for the page but it keeps throwing a 404 error. Could someone please look over my code and help me figure out the issue?
add_post.html:
{% extends "base.html" %}
{% block content %}
<header>
<div >
<div >
<h1 >Add Your Post</h1>
<p >Tell us about your favourite game</p>
</div>
</div>
</header>
{%endblock%}
views.py:
from django.shortcuts import render, get_object_or_404, reverse
from django.views.generic import View, CreateView, ListView
from django.http import HttpResponseRedirect
from .models import Post
from .forms import CommentForm
class AddPost(CreateView):
model = Post
template_name = 'add_post.html'
fields = '__all__'
urls.py:
from .views import AddPost, PostList, PostDetail, PostLike
from django.urls import path
urlpatterns = [
path('', PostList.as_view(), name='home'),
path('<slug:slug>/', PostDetail.as_view(), name='post_detail'),
path('like/<slug:slug>/', PostLike.as_view(), name='post_like'),
path('add_post/', AddPost.as_view(), name='create_post'),
]
CodePudding user response:
The order of the URL pattern is sensitive. You have a "catchall" URL defined with path('<slug:slug>/', PostDetail.as_view(), name='post_detail'),
.
Therefor add_post
could be a valid slug for a post, which is causing the conflict.
Just change the order of your URL patterns to the following:
from .views import AddPost, PostList, PostDetail, PostLike
from django.urls import path
urlpatterns = [
path('', PostList.as_view(), name='home'),
path('like/<slug:slug>/', PostLike.as_view(), name='post_like'),
path('add_post/', AddPost.as_view(), name='create_post'),
path('<slug:slug>/', PostDetail.as_view(), name='post_detail'),
]