I am trying to create a new post and when I click on the save button, I get error as stated in the image. But when I go to the post list page, the post is created. I am not able to understand the error and where to look for it. I am new at django. Please help!
Main-urls.py file:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from django.contrib.auth import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('blog_app.urls', namespace='blog_app')),
url(r'^accounts/',include('accounts.urls', namespace='accounts')),
#path('accounts/login/', views.LoginView.as_view(template_name='blog_app/login.html'),name='login'),
#path('accounts/logout/',views.LogoutView.as_view(template_name='blog_app/base.html'),name='logout'),
]
blog_app-urls.py file:
from django.conf.urls import url
from blog_app import views
from django.urls import path
app_name = 'blog_app'
urlpatterns = [
url(r'^$', views.PostListView.as_view(),name='post_list'),
url(r'^about/$', views.AboutView.as_view(),name='about'),
url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(),name='post_detail'),
url(r'^post/new/$', views.CreatePostView.as_view(),name='new_post'),
url(r'^post/(?P<pk>\d+)/edit/$', views.UpdatePostView.as_view(),name='edit_post'),
url(r'^drafts/$', views.DraftListView.as_view(),name='draft_post_list'),
url(r'^post/(?P<pk>\d+)/remove/$', views.DeletePostView.as_view(),name='delete_post'),
# url(r'^post/(?P<pk>\d+)/remove/$', views.post_remove,name='delete_post'),
url(r'^post/(?P<pk>\d+)/publish/$', views.post_publish, name='post_publish'),
url(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'),
url(r'^comment/(?P<pk>\d+)/approve/$', views.comment_approve, name='comment_approve'),
url(r'^comment/(?P<pk>\d+)/remove/$', views.comment_remove, name='comment_remove'),
# path('register/',views.register,name='register'),
]
blog_app-views.py file:
from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from blog_app.models import Post,Comment
from blog_app.forms import PostForm,CommentForm
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.views.generic import (TemplateView,ListView,DetailView,CreateView,
UpdateView,DeleteView)
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login,logout,authenticate
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(publish_date__lte = timezone.now()).order_by('-publish_date')
class PostDetailView(DetailView):
model = Post
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = 'accounts/login/'
redirect_field_name = 'blog_app/post_detail.html'
form_class = PostForm
model = Post
class UpdatePostView(LoginRequiredMixin,UpdateView):
login_url = 'accounts/login/'
redirect_field_name = 'blog_app/post_detail.html'
form_class = PostForm
model = Post
class DraftListView(LoginRequiredMixin,ListView):
login_url = 'accounts/login/'
redirect_field_name = 'blog_app/post_draft_list.html'
model = Post
def get_queryset(self):
return Post.objects.filter(publish_date__isnull=True).order_by('-create_date')
class DeletePostView(LoginRequiredMixin,DeleteView):
model = Post
success_url = reverse_lazy('post_list')
blog_app-models.py file:
from django.db import models
from django.utils import timezone
from django.urls import reverse
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=150)
text = models.TextField()
create_date = models.DateTimeField(default=timezone.now)
publish_date = models.DateTimeField(blank=True,null=True)
# add in thumbnail later
def publish(self):
self.publish_date = timezone.now()
self.save()
def approveComment(self):
return self.comments.filter(approve_comment=True)
def get_absolute_url(self):
return reverse("post_detail",kwargs={'pk':self.pk})
def __str__(self):
return self.title
def snippet(self):
return self.text[:100] + '...'
class Comment(models.Model):
post = models.ForeignKey('blog_app.Post',related_name='comments', on_delete=models.CASCADE)
author = models.CharField(max_length=150)
text = models.TextField()
create_date = models.DateTimeField(default=timezone.now)
approve_comment = models.BooleanField(default=False)
def approve(self):
self.approve_comment = True
self.save()
def get_absolute_url(self):
return reverse("post_list")
def __str__(self):
return self.text
base.html file:
<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
<title>MyBlog</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
{# MEDIUM STYLE EDITOR#}
<script src="//cdn.jsdelivr.net/medium-editor/latest/js/medium-editor.min.js"></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/medium-editor/latest/css/medium-editor.min.css" type="text/css" media="screen" charset="utf-8">
{# Custom CSS#}
<link rel="stylesheet" href="{% static 'css/blog_app.css' %}">
{# Fonts#}
<link href="https://fonts.googleapis.com/css?family=Montserrat|Russo+One" rel="stylesheet">
<body class='loader'>
<nav class="navbar navbar-default techfont custom-navbar">
<div class="container">
<ul class="nav navbar-nav">
<li><a class='navbar-brand bigbrand' href="{% url 'blog_app:post_list' %}">Home</a></li>
<li><a href="{% url 'blog_app:about'%}">About</a></li>
<li><a href="https://www.github.com">Github</a></li>
<li><a href="https://www.linkedin.com">LinkedIn</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
{% if user.is_authenticated %}
<li>
<a href="{% url 'blog_app:new_post' %}" >New Post</a>
</li>
<li>
<a href="{% url 'blog_app:draft_post_list' %}">Drafts</a>
</li>
<li>
<a href="{% url 'accounts:logout' %}" >Logout</a>
</li>
<li>
<a >Welcome: {{ user.username }}</a>
</li>
{% else %}
<li><a class='nav navbar-right' href="{% url 'accounts:login' %}" >Login</a></li>
{% endif %}
</ul>
</div>
</nav>
{# The actual blog posts#}
<div class="content container">
<div class="row">
<div class="col-md-8">
<div class="blog_posts">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</div>
{# SCRIPTS#}
<script type="text/javascript" src="{% static 'js/blog.js' %}"></script>
</body>
</html>
post_list.html file:
{% extends 'blog_app/base.html' %}
{% block content %}
<div class="centerstage">
{% for post in post_list %}
<div class="post">
<h1><a href="{% url 'blog_app:post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
<p>{{ post.snippet }}</p>
<div class="date">
<p><b>Published on: </b> {{ post.publish_date|date:"D M Y"}}</p>
</div>
<a href="{% url 'blog_app:post_detail' pk=post.pk %}">Comments: {{ post.approveComment.count }}</a>
</div>
{% endfor %}
</div>
{% endblock %}
post_detail.html file:
{% extends 'blog_app/base.html' %}
{% block content %}
<h1 class='posttitle loader'>{{ post.title }}</h1>
{% if post.publish_date %}
<div class="date postdate">
{{ post.publish_date }}
</div>
{% else %}
<a class="btn btn-default" href="{% url 'blog_app:post_publish' pk=post.pk %}">Publish</a>
{% endif %}
<p class='postcontent' >{{ post.text|safe|linebreaksbr }}</p>
{% if user.is_authenticated %}
<a class="btn btn-primary" href="{% url 'blog_app:edit_post' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
<a class="btn btn-primary" href="{% url 'blog_app:delete_post' pk=post.pk %}"><span class="glyphicon glyphicon-remove"></span></a>
{% endif %}
<hr>
<a class="btn btn-primary btn-comment" href="{% url 'blog_app:add_comment_to_post' pk=post.pk %}">Add comment</a>
<div class="container">
{% for comment in post.comments.all %}
<br>
{% if user.is_authenticated or comment.approve_comment %}
{{ comment.create_date }}
{% if not comment.approve_comment %}
<a class="btn btn-default" href="{% url 'blog_app:comment_remove' pk=comment.pk %}"><span class="glyphicon glyphicon-remove"></span></a>
<a class="btn btn-default" href="{% url 'blog_app:comment_approve' pk=comment.pk %}"><span class="glyphicon glyphicon-ok"></span></a>
{% endif %}
<p>{{ comment.text|safe|linebreaks }}</p>
<p>Posted by: <strong>{{ comment.author }}</strong></p>
{% endif %}
{% empty %}
<p>No comments posted.</p>
{% endfor %}
</div>
{% endblock %}
In blog_app-models.py
, you write
class Post(models.Model):
...
def get_absolute_url(self):
return reverse("post_detail",kwargs={'pk':self.pk})
You forget to account for the fact the post_detail
is namespaced under blog_app
where it is include
'd in Main-urls.py
. To correctly reverse this URL, you will need to write
reverse("blog_app:post_detail",kwargs={'pk':self.pk})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.