问题
I've been trying to get this app to work, I run: python manage.py runserver - & everything was fine, I was able to see the website, login as a superuser, make a comment, however in trying to view the post I started to get an error. Now, if I just go to the site, i get an error. I get this error message:
File "/Users/homepage/opt/anaconda3/envs/MyDjangoEnv/lib/python3.8/site-packages/django/urls/resolvers.py", line 685, in _reverse_with
_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['
post/(?P<pk>\\d+)$']
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'post_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P<pk>\\d+)$']
The browser highlights this line as the problem(it is in my base.html page shown below. This link is something I pasted from bootstrap cdn (the link is from 2 years ago). Th entire base.html is given below):
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
11
I found a link that may be applicable to my problem here: NoReverseMatch at / list where he says:
You are mixing two syntax variants to specify patterns. Since django-2.0 there are two ways to specify URL patterns: with path(..) [Django-doc], and with re_path(..) [Django-doc] for regular expressions-like patterns (an alias is url(..) [Django-doc]).
You however mix the two. You can use the two concurrently, but you need to specify per urlpatterns entry the correct one:
# app/urls.py
from django.urls import path, re
urlpatterns = [
url(r'^$', views.news_list, name='news_list'),
path('single/<int:pk>/', views.new_single, name="new_single"),
]
but I don't know how to apply this to my application. It might be relevant as I am following a tutorial that was made 2 years ago and is using an older version of python, i think 1. something, whereas I am using 3.8.. any help would be greatly appreciated, as I'm stuck.
mysite/blog/urls.py:
from django.conf.urls import url
from blog import views
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='post_new'),
url(r'^post/(?P<pk>\d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'),
url(r'^post/(?P<pk>\d+)/remove/$',views.PostDeleteView.as_view(),name='post_remove'),
url(r'^drafts/$',views.DraftListView.as_view(),name='post_draft_list'),
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'),
url(r'^post/(?P<pk>\d+)/publish/$',views.post_publish,name='post_publish'),
]
mysite/mysite/urls.py:
from django.conf.urls import url,include
from django.contrib import admin
from django.urls import path
from django.contrib.auth import views
urlpatterns = [
path(r'^admin/', admin.site.urls),
url(r'',include('blog.urls')),
url(r'^silk/', include('silk.urls', namespace='silk')),
url(r'^login/$', views.LoginView.as_view(), name='login'),
url(r'^logout/$', views.LogoutView.as_view(), name='logout',kwargs={'next_page':'/'}),
]
mysite/blog/templates/models.py:
from django.db import models
from django.utils import timezone
from django.urls import reverse
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User',on_delete=models.CASCADE,)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now())
published_date = models.DateTimeField(blank=True,null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def approve_comments(self):
return self.comments.filter(approved_comment=True)
def get_absolute_url(self):
# return reverse("post_detail",kwargs={'pk':self.pk})
return reverse("post_detail", kwargs={'pk':self.pk})
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('blog.Post',related_name='comment',on_delete=models.CASCADE,)
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now())
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def get_absolute_url(self):
return reverse('post_list')
def __str__(self):
return self.text
mysite/blog/templates/blog/base.html:
<!DOCTYPE html
{% load static %}
<html>
<head>
<meta charset="utf-8">
<title>Blog</title>
<!-- Bootstrap -->
<!-- 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.css' %}">
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Montserrat|Russo+One" rel="stylesheet">
</head>
<body class="loader">
<!-- Navbar -->
<nav class="navbar navbar-default techfont custom-navbar">
<div class="container">
<ul class="nav navbar-nav">
<li><<a class='navbar-brand bigbrand' href="{% url 'post_list'%}">My blog</a></li>
<li><<a href="{%url 'about' %}">About</a></li>
<li><<a href="http://www.github.com">Github</a></li>
<li><<a href="http://www.linkedin.com"</a>linkedin</li>
</ul>
<ul class='nav navbar-nav navbar-right'>
{% if user.is_authenticated %}
<li>
<<a href="{% url 'post_new' %}">New Post</a>
</li>
<li>
<a href="{% url 'post_draft_list' %}">Drafts</a>
</li>
<li>
<<a href="{% url 'logout' %}">Log out</a>
</li>
<li>
<a> Welcome: {{user.username}}</a>
</li>
{% else%}
<li><<a class='nav navbar-right' href="{%url 'login'%}"><span class='glyphicon glyphicon-user'></span></a></li>
{%endif %}
</ul>
</div>
</nav>
<!-- Content block -->
<div class="content container">
<div class="row">
<div class="col-md-8">
<div class="blog_posts">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</div>
</body>
</html>
mysite/blog/views.py
from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from blog.models import Post,Comment
from blog.forms import PostForm,CommentForm
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
class PostDetailView(DetailView):
model = Post
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class PostUpdateView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
#delete post
class PostDeleteView(LoginRequiredMixin,DeleteView):
model = Post
success_url = reverse_lazy('post_list')
#unpublished drafts
class DraftListView(LoginRequiredMixin,ListView):
login_url = '/login'
redirect_field_name = 'blog/post_list.html'
def get_queryset(self):
return Post.objects.filter(published_date__isnull=True).order_by('created_date')
########################
@login_required
def post_publish(request,pk):
post = get_object_or_404(Post,pk=pk)
post.publish
return redirect('post_detail',pk=pk)
@login_required
def add_comment_to_post(request,pk):
post = get_object_or_404(Post,pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail',pk=post.pk)
else:
form = CommentForm()
return render(request,'blog/commment_form.html',{'form':form})
@login_required
def comment_approve(request,pk):
comment = get_object_or_404(Comment,pk=pk)
comment.approve()
return redirect('post_detail',pk=comment.post.pk)
@login_required
def comment_remove(request,pk):
comment_pk = comment.post.pk
comment.delete()
return redirect('post_detail',pk=post_pk)
mysite/mysite/settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 3.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'blog/templates/blog')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+$0zreau)2tit=6_^(v56@!z1*%*j%x^9mul40b-@#xlt*e9s1'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'silk',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'silk.middleware.SilkyMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR , 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
LOGIN_REDIRECT_URL = '/'
mysite/blog/templates/blog/post_draft_list.html
{% extends "blog/base.html" %}
{%block content %}
{% for post in posts %}
<div class="post">
<p class='date'>created: {{ post.created_date|date:'d-m-Y'}}</p>
<h1><<a href="{%url 'post_detail' pk=post.pk %}">{{post.title}}</a></h1>
<p>{{post.text|truncatechars:200}}</p>
</div>
{%endfor%}
{% endblock%}
mysite/blog/templates/blog/post_list.html
{% extends "blog/base.html" %}
{%block content %}
<div class="centerstage">
{% for post in post_list%}
<div class="post">
<h1><a href="{%url 'post_detail' pk=post.pk%}">{{ post.title }}</a></h1>
<div class="date">
<p>Published on: {{post.published|date:"D M Y"}}</p>
</div>
<a href="{% url 'post_detail' pk=post_pk %}">Comments: {{post.approve_comments }}</a>
</div>
{%endfor%}
</div>
{% endblock%}
mysite/blog/templates/blog/post_detail.html
{% extends "blog/base.html" %}
{%block content %}
<h1 class="posttitle loader">{{post.title}}</h1>
{% if post.published_date %}
<div class="date postdate">
{{ post.published_date}}
</div>
{%else %}
<a class="btn btn-default" href="{% url 'post_publish' pk=post.pk %}">Publish</a>
{%endif %}
<p class='postcontent'>{{ post.title|safe|linebreaksbr}}</p>
{% if user.is_authenticated %}
<a class='btn btn-primary' href="{% url 'post_edit' pk=post.pk%}">
<span class='glyphicon glyphicon-pencil'></span>
</a>
<a class='btn btn-primary' href="{% url 'post_remove' pk=post.pk%}">
<span class='glyphicon glyphicon-remove'></span>
</a>
{%endif%}
<hr>
<a class=btn btn-primary btn-comment href="% url '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_approved_comment %}
{{comment.created_date}}
{% if not comment_approved_comment%}
<a class='btn btn-primary' href="{% url 'comment_remove' pk=comment.pk%}">
<span class='glyphicon glyphicon-remove'></span>
</a>
<a class='btn btn-primary' href="{% url 'comment_approve' pk=post.pk%}">
<<span class='glyphicon glyphicon-ok'></span>
</a>
{%endif %}
<p>{{comment.text|safe|linebreaks}}</p>
<p>Posted by: {{comment.author}}</p>
{%endif %}
{%empty %}
<p>no comments</p>
{% endfor %}
</div>
{% endblock%}
new errors traceback:
when I hit drafts I get this error:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/drafts/
Django Version: 3.1.1
Python Version: 3.8.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/views/generic/list.py", line 142, in get
self.object_list = self.get_queryset()
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/views/generic/list.py", line 35, in get_queryset
raise ImproperlyConfigured(
Exception Type: ImproperlyConfigured at /drafts/
Exception Value: DraftListView is missing a QuerySet. Define DraftListView.model, DraftListView.queryset, or override DraftListView.get_queryset().
and then when I hit 'add comment' I get this error:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/post/1/comment/
Django Version: 3.1.1
Python Version: 3.8.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template loader postmortem
Django tried loading these templates, in this order:
Using engine django:
* django.template.loaders.filesystem.Loader: /Users/homepage/Desktop/My_Django_Stuff/blog_project/mysite/blog/templates/blog/blog/commment_form.html (Source does not exist)
* django.template.loaders.app_directories.Loader: /Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/contrib/admin/templates/blog/commment_form.html (Source does not exist)
* django.template.loaders.app_directories.Loader: /Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/contrib/auth/templates/blog/commment_form.html (Source does not exist)
* django.template.loaders.app_directories.Loader: /Users/homepage/Desktop/My_Django_Stuff/blog_project/mysite/blog/templates/blog/commment_form.html (Source does not exist)
Traceback (most recent call last):
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/Users/homepage/Desktop/My_Django_Stuff/blog_project/mysite/blog/views.py", line 71, in add_comment_to_post
return render(request,'blog/commment_form.html',{'form':form})
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/template/loader.py", line 61, in render_to_string
template = get_template(template_name, using=using)
File "/Users/homepage/opt/anaconda3/lib/python3.8/site-packages/django/template/loader.py", line 19, in get_template
raise TemplateDoesNotExist(template_name, chain=chain)
Exception Type: TemplateDoesNotExist at /post/1/comment/
Exception Value: blog/commment_form.html
来源:https://stackoverflow.com/questions/64084918/noreversematch-at-reverse-for-post-detail-with-keyword-arguments-pk