亲爱的,你好。我是django的新手。我正在尝试使用django创建博客,但是现在每当我单击链接时,都在页面未找到错误困扰。 127.0.0.1:8000/post.html返回错误页面。请帮助我。
下面是我的代码。
这是我的 views.py 文件:
from django.db.models import Count, Q
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render, get_object_or_404, redirect, reverse
from django.views.generic
import View, ListView, DetailView, CreateView, UpdateView, DeleteView
from .forms import CommentForm, PostForm
from .models import Post, Author, PostView
from marketing.forms import EmailSignupForm
from marketing.models import Signup
form = EmailSignupForm()
def get_author(user):
qs = Author.objects.filter(user=user)
if qs.exists():
return qs[0]
return None
class SearchView(View):
def get(self, request, *args, **kwargs):
queryset = Post.objects.all()
query = request.GET.get('q')
if query:
queryset = queryset.filter(
Q(title__icontains=query) | Q(overview__icontains=query)
).distinct()
context = {
'queryset': queryset
}
return render(request, 'search_results.html', context)
def search(request):
queryset = Post.objects.all()
query = request.GET.get('q')
if query:
queryset = queryset.filter(Q(title__icontains=query) | Q(overview__icontains=query)).distinct()
context = {
'queryset': queryset
}
return render(request, 'search_results.html', context)
def get_category_count():
queryset = Post.objects.values('categories__title').annotate(Count('categories__title'))
return queryset
class IndexView(View):
form = EmailSignupForm()
def get(self, request, *args, **kwargs):
featured = Post.objects.filter(featured=True)
latest = Post.objects.order_by('-timestamp')[0:3]
context = {
'object_list': featured,
'latest': latest,
'form': self.form
}
return render(request, 'index.html', context)
def post(self, request, *args, **kwargs):
email = request.POST.get("email")
new_signup = Signup()
new_signup.email = email
new_signup.save()
messages.info(request, "Successfully subscribed")
return redirect("home")
def index(request):
featured = Post.objects.filter(featured=True)
latest = Post.objects.order_by('-timestamp')[0:3]
if request.method == "POST":
email = request.POST["email"]
new_signup = Signup()
new_signup.email = email
new_signup.save()
context = {
'object_list': featured,
'latest': latest,
'form': form
}
return render(request, 'index.html', context)
class PostListView(ListView):
form = EmailSignupForm()
model = Post
template_name = 'blog.html'
context_object_name = 'queryset'
paginate_by = 1
def get_context_data(self, **kwargs):
category_count = get_category_count()
most_recent = Post.objects.order_by('-timestamp')[:3]
context = super().get_context_data(**kwargs)
context['most_recent'] = most_recent
context['page_request_var'] = "page"
context['category_count'] = category_count
context['form'] = self.form
return context
def post_list(request):
category_count = get_category_count()
most_recent = Post.objects.order_by('-timestamp')[:3]
post_list = Post.objects.all()
paginator = Paginator(post_list, 4)
page_request_var = 'page'
page = request.GET.get(page_request_var)
try:
paginated_queryset = paginator.page(page)
except PageNotAnInteger:
paginated_queryset = paginator.page(1)
except EmptyPage:
paginated_queryset = paginator.page(paginator.num_pages)
context = {
'queryset': paginated_queryset,
'most_recent': most_recent,
'page_request_var': page_request_var,
'category_count': category_count,
'form': form
}
return render(request, 'blog.html', context)
class PostDetailView(DetailView):
model = Post
template_name = 'post.html'
context_object_name = 'post'
form = CommentForm()
def get_object(self):
obj = super().get_object()
if self.request.user.is_authenticated:
PostView.objects.get_or_create(
user=self.request.user,post=obj)
return obj
def get_context_data(self, **kwargs):
category_count = get_category_count()
most_recent = Post.objects.order_by('-timestamp')[:3]
context = super().get_context_data(**kwargs)
context['most_recent'] = most_recent
context['page_request_var'] = "page"
context['category_count'] = category_count
context['form'] = self.form
return context
def post(self, request, *args, **kwargs):
form = CommentForm(request.POST)
if form.is_valid():
post = self.get_object()
form.instance.user = request.user
form.instance.post = post
form.save()
return redirect(reverse("post-detail", kwargs={'pk': post.pk}))
def post_detail(request, id):
category_count = get_category_count()
most_recent = Post.objects.order_by('-timestamp')[:3]
post = get_object_or_404(Post, id=id)
if request.user.is_authenticated:
PostView.objects.get_or_create(user=request.user, post=post)
form = CommentForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.instance.user = request.user
form.instance.post = post
form.save()
return redirect(reverse("post-detail", kwargs={'id': post.pk}))
context = {
'post': post,
'most_recent': most_recent,
'category_count': category_count,
'form': form
}
return render(request, 'post.html', context)
class PostCreateView(CreateView):
model = Post
template_name = 'post_create.html'
form_class = PostForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = 'Create'
return context
def form_valid(self, form):
form.instance.author = get_author(self.request.user)
form.save()
return redirect(reverse("post-detail", kwargs={'pk': form.instance.pk}))
def post_create(request):
title = 'Create'
form = PostForm(request.POST or None, request.FILES or None)
author = get_author(request.user)
if request.method == "POST":
if form.is_valid():
form.instance.author = author
form.save()
return redirect(reverse("post-detail", kwargs={'id': form.instance.id}))
context = {
'title': title,
'form': form
}
return render(request, "post_create.html", context)
这是我的 post.html 文件:
{% extends 'base.html' %} {% load static %}
{% block content %}
<style>
.post-body img {
width: 100%;
}
</style>
<div class="container">
<div class="row">
<!-- Latest Posts -->
<main class="post blog-post col-lg-8">
<div class="container">
<div class="post-single">
<div class="post-thumbnail"><img src="{{ post.thumbnail.url }}" alt="..." class="img-fluid"></div>
<div class="post-details">
<div class="post-meta d-flex justify-content-between">
<div class="category">
{% for cat in post.categories.all %}
<a href="#">{{ cat }}</a>
{% endfor %}
</div>
<div>
<a href="{% url 'post-update' pk=post.pk %}">Update</a>
<a href="{% url 'post-delete' pk=post.pk %}">Delete</a>
</div>
</div>
<h1>{{ post.title }}<a href="#"><i class="fa fa-bookmark-o"></i></a></h1>
<div class="post-footer d-flex align-items-center flex-column flex-sm-row"><a href="#" class="author d-flex
align-items-center flex-wrap">
<div class="avatar"><img src="{{ post.author.profile_picture.url }}" alt="..." class="img-fluid"></div>
<div class="title"><span>{{ post.author.user.username }}</span></div></a>
<div class="d-flex align-items-center flex-wrap">
<div class="date"><i class="icon-clock"></i> {{ post.timestamp|timesince }} ago</div>
<div class="views"><i class="icon-eye"></i> {{ post.view_count }}</div>
<div class="comments meta-last"><i class="icon-comment"></i>{{ post.comment_count }}</div>
</div>
</div>
<div class="post-body">
{{ post.content | safe }}
</div>
<div class="posts-nav d-flex justify-content-between align-items-stretch flex-column flex-md-row">
{% if post.previous_post %}
<a href="{{ post.previous_post.get_absolute_url }}" class="prev-post text-left d-flex align-items-center">
<div class="icon prev"><i class="fa fa-angle-left"></i></div>
<div class="text"><strong class="text-primary">Previous Post </strong>
<h6>{{ post.previous_post.title }}</h6>
</div>
</a>
{% endif %}
{% if post.next_post %}
<a href="{{ post.next_post.get_absolute_url }}" class="next-post text-right d-flex align-items-center
justify-content-end">
<div class="text"><strong class="text-primary">Next Post </strong>
<h6>{{ post.next_post.title }}</h6>
</div>
<div class="icon next"><i class="fa fa-angle-right"> </i></div>
</a>
{% endif %}
</div>
<div class="post-comments">
<header>
<h3 class="h6">Post Comments<span class="no-of-comments">({{ post.comments.count }})</span></h3>
</header>
{% for comment in post.get_comments %}
<div class="comment">
<div class="comment-header d-flex justify-content-between">
<div class="user d-flex align-items-center">
<div class="image">
{% if comment.user.author %}
<img src="{{ comment.user.author.profile_picture.url }}" alt="..." class="img-fluid
rounded-circle">
{% else %}
<img src="{% static 'img/user.svg' %}" alt="..." class="img-fluid rounded-circle">
{% endif %}
</div>
<div class="title"><strong>{{ comment.user.username }}</strong><span class="date">{{
comment.timestamp|timesince }} ago</span></div>
</div>
</div>
<div class="comment-body">
<p>{{ comment.content }}</p>
</div>
</div>
{% endfor %}
</div>
{% if request.user.is_authenticated %}
<div class="add-comment">
<header>
<h3 class="h6">Leave a reply</h3>
</header>
<form method="POST" action="." class="commenting-form">
{% csrf_token %}
<div class="row">
<div class="form-group col-md-12">
{{ form }}
</div>
<div class="form-group col-md-12">
<button type="submit" class="btn btn-secondary">Submit Comment</button>
</div>
</div>
</form>
</div>
{% else %}
<a href="{% url 'account_login' %}" class="btn btn-primary">Login to comment</a>
{% endif %}
</div>
</div>
</div>
</main>
{% include 'sidebar.html' with most_recent=most_recent category_count=category_count %}
</div>
</div>
{% endblock content %}
这是我的 urls.py 文件:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from posts.views import (
index,search,post_list,post_detail,post_create,
post_update,post_delete,
IndexView,PostListView,PostDetailView,
PostCreateView,PostUpdateView,PostDeleteView
)
from marketing.views import email_list_signup
urlpatterns = [
path('admin/', admin.site.urls),
path('', IndexView.as_view(), name='home'),
path('blog/', PostListView.as_view(), name='post-list'),
path('search/', search, name='search'),
path('email-signup/', email_list_signup, name='email-list-signup'),
path('create/', PostCreateView.as_view(), name='post-create'),
path('post/<pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/<pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('tinymce/', include('tinymce.urls')),
path('accounts/', include('allauth.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)