Django 1.10 doesn't show post from db - python

I'm learning django framework writing a blog. I've added some posts in django-admin and I want to show them on web.
MODELS.PY
from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset()\
.filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Roboczy'),
('publish', 'Opublikowany')
)
title = models.CharField(max_length=300)
slug = models.SlugField(max_length=300, unique_for_date='publish')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=20,
choices=STATUS_CHOICES,
default='draft')
object = models.Manager()
published = PublishedManager()
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
VIEWS.PY
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.published.all()
return render(request,
'blog/post/list.html',
{'posts': posts})
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status ='published',
publish_year=year,
publish_month=month,
publish_day=day)
return render(request,
'blog/post/detail.html',
{'post': post})
URLS.PY at BLOG APP
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$'
r'(?P<post>[-\w]+)/$',
views.post_detail,
name='post_detail'),
]
URLS.PY (project level)
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/', include('blog.urls',
namespace='blog',
app_name='blog')),
]
list.html
{% extends "blog/base.html" %}
{% block title %}My Blog {% endblock %}
{% block content %}
<h1>Mój BLOG</h1>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p>
Opublikowane {{ post.publish }} przez {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks}}
{% endfor %}
{% endblock %}
I don't know why these posts aren't shown on list.html. I think the mistake is in get_absolute_url.

Instead of posts = Post.published.all()
Try
posts = Post.objects.all()

Ok it's work i must change posts = Post.objects.all() and on list.htlm
<a href="{{ post.get_absolute_url }}">
to
<a href="{{ posts }}">

Urlpatterns are wrong.
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$'
r'(?P<post>[-\w]+)/$',
views.post_detail,
name='post_detail'),
According to the views the url pattern should be:
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$',
views.post_detail,
name='post_detail'),
Also, Views are wrong:
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status ='published',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request,
'blog/post/detail.html',
{'post': post})
Please note that query fields are publish__year (not publish_year), publish___month(not publish_month) and publish__date( not publish_date)
Once you make these changes, the get_absolute_url will also work fine.
I don't know if you want to use Post.objects.all() or Post.published.all(). Ideally, it should be Post.published.all() because in general, only published posts are displayed.

Related

I am using CreateView in django but getting error- The view blog.views.PostCreateView didn't return an HttpResponse object. It returned None instead

I am having a post model with a user having OneToMany Relationship with inbuilt user model for authentication
my urls.py
from django.contrib import admin
from django.urls import path, include
# from views import PostView
from . import views
urlpatterns = [
path('', views.PostView.as_view(), name='blogHome'),
path('post/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'),
path('post/new/', views.PostCreateView.as_view(), name='post-create'),
path('about/', views.about, name='about')
]
my views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Post
from django.views.generic import (
ListView,
DetailView,
CreateView
)
# Create your views here.
def home(request):
context = {
'posts': Post.objects.all()
}
return render(request, 'blog/home.html', context)
def about(request):
return render(request, 'blog/about.html')
class PostView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_published']
class PostDetailView(DetailView):
model = Post
class PostCreateView(CreateView):
model = Post
fields = ['title', 'body']
#to add author before validation
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
Post Model
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
body = models.TextField()
date_published = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
I am using post_form.html as the template name
post_form.html
{% extends 'blog/layout.html' %}
{% load crispy_forms_tags %}
{% block body %}
<div class="content-section p-20">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group p-30">
<legend class="border-bottom mb-4">Create new post</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Create</button>
</div>
</form>
</div>
{% endblock %}
I am a beginner in Django , please tell if anything more is needed to solve the problem. Also why this type of error is coming only with Createview and not with other views
Apparently the return of super().form_valid(form) is None and not a valid response. I don't know much of this design pattern in Django but seeing your other methods seems like this view is decorated by some method which returns a valid response. So you should not return something in your implementation. So, drop the return and test again.

Variables are not rendering

I’m making a blog site. And I have been trying to render from a model, RecentPosts, objects rpost1, etc. in my template blogs -file base.html which is my blog's details page.
But it is not rendering. Is there a solution?
File views.py
from django.http import HttpResponse
from django.shortcuts import render
from blog.models import Post
from django.contrib import messages
from django.views.generic import ListView, DetailView
from .models import Post, RecentPosts, Comment, Contact, Populars
from datetime import datetime
from .forms import CommentForm
def index(request):
return render(request, 'index.html')
def path(request):
return render(request, 'blog.html')
def cv(request):
return render(request, 'cv.html')
class HomeView(ListView):
model = Post
template_name = 'listview.html'
class ArticleDetailView(DetailView):
model = Post
template_name = 'base2.html'
def rpost(request):
template_name = "blogs-base.html"
rpost = RecentPosts.objects.all()
context = {'rpost': 'rpost'}
return render(request, template_name, context)
This is the URL portion.
File urls.py
from django.urls import path
from . import views
from .views import HomeView, ArticleDetailView, contact, Comment_page, popular
urlpatterns = [
path('', views.index, name='index'),
path('index.html', views.index, name='index'),
path('cv.html', views.cv, name='cv'),
path('blogs/', views.HomeView.as_view(), name="blogs"),
path('blogs/<slug:slug>', ArticleDetailView.as_view(), name='base2'),
path('contact/', views.contact, name='contact'),
path('contact.html/', views.contact, name='contact'),
path('comment.html/', views.Comment_page, name='comment'),
path('popular', views.popular, name='popular'),
]
This is the model portion.
File models.py
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.timezone import now
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=120)
author_name = models.CharField(max_length=120)
author_description = models.CharField(max_length=120)
body = models.TextField(default='')
slug = models.CharField(max_length = 130)
timestamp = models.DateTimeField(auto_now=True)
def get_abosolute_url(self):
return reverse()
class Comment(models.Model):
post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name='comments')
user = models.CharField(max_length=200)
message = models.TextField()
timestamp = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.capitalize() + ' : ' + self.message[0:16] + '........'
class Contact(models.Model):
email = models.CharField(max_length=20)
message = models.CharField(max_length=200)
models.CharField(max_length=200)
class RecentPosts(models.Model):
rpost1 = models.CharField(max_length=120)
rpost2 = models.CharField(max_length=120)
rpost3 = models.CharField(max_length=120
)
File blogs-base.html
<a href="marketing-single.html" class="list-group-item list-group-item-action flex-column align-items-start">
<div class="w-100 justify-content-between">
<img src="assets/blog-uploads/ad.png" alt="" class="img-fluid float-left">
{% for i in rpost %} <h5 class="mb1">{{i.rpost1}}</h5>
<small>12 Jan, 2016</small>{% endfor %}
</div>
</a>
This is the listview where I’m posting only my blog's thumbnails.
File listview.html
{% extends 'blogs-base.html' %}
{% load static %}
{% block title %}{{post.title}}{% endblock %}
{% block content %}
{% for post in object_list %}
<div class="col-lg-6">
<div class="blog-box">
<div class="post-media">
<a href="marketing-single.html" title="">
<img src="{% static 'website/assets/blog-uploads/ad.png' %}" alt="" class="img-fluid">
<div class="hovereffect">
<span class=""></span>
</div><!-- end hover -->
</a>
</div><!-- end media -->
<div class="blog-meta">
<h4>{{post.title}}</h4>
<small></small>
<small>20 July, 2017</small><br><br>
</div><!-- end meta -->
</div><!-- end blog-box -->
</div><!-- end col -->
{% endfor %}
{% endblock %}
You made a mistake in your context. You're are passing a string of 'rpost' instead of
context = { "rpost" : rpost }

Django: "No comment found matching the query" 404 Error

I'm making a simple blog app with comments on a 'posts detail view' page, but I'm getting a 404 error saying "No comment found matching the query" whenever I try submitting my comment. Everything else in the app works except for the comments. I'm new to django and am making this site to learn, would appreciate any help!
Views.py
class PostDetailView(DetailView):
model = Post
fields = ['content']
class CommentCreateView(LoginRequiredMixin, CreateView):
model = Comment
fields = ['content']
template_name = 'blog/comment.html'
def form_valid(self, form):
post = self.get_object()
form.instance.author = self.request.user
return super().form_valid(form)
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ['-date_posted']
def __str__(self):
return f'Comment {self.content} by {self.author.username}'
def get_absolute_url(self):
return reverse('comment', kwargs={'pk': self.pk})
urls.py
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
CommentCreateView
)
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('post/comment/<int:pk>/', CommentCreateView.as_view(), name='create'),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('about/', views.about, name='blog-about'),
]
comments.html This is the form. It's supposed to redirect to a different form to comment then back to post detail view
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Comment</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Post</button>
</div>
</form>
</div>
{% endblock content %}

No Post matches the given query.in django

am using django 2.0 and here is the problem
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/blog/post-detail/
Raised by: blog.views.post_detail
No Post matches the given query.
here is the blog/urls
from django.urls import path,include
from .import views
urlpatterns = [
path('blog/',views.post_list,name="post_list"),
path('blog/post-detail/',views.post_detail,name="post_detail"),
]
and views.py
from django.shortcuts import render,get_object_or_404
from.models import Post
# Create your views here.
def post_list(request):
object_list=Post.objects.all()
context={
'object_list': object_list,
}
return render(request,"blog.html",context)
def post_detail(request,slug=None):
post=get_object_or_404(Post,slug=slug)
context={
'post':post,
}
return render(request,"post_detail.html",context)
and the post_detail.html
{% extends "base.html" %}
{% load static %}
{% block seo_title %}{% endblock %}
{% block seo_description %}{% endblock %}
{% block Content %}
<article>
<div class="embed-responsive embed-responsive-16by9">
<img src="images/blog1.jpg" alt="" />
</div>
<div class="post-content">
<h2>{{post.title}}</h2>
<div>
{{post.created}} Author {{Post.user}}
<hr/>
<p>{{post.body}}</p>
</article>
{% endblock Content %}
CAN ANYONE HELP ON THIS THE ONLY PROBLEM I SEE THAT SLUG THING I MUST HAVE CONFUSED SOMEWHERE
blog.html
<!-- Blog -->
<div class="blog">
<div class="row">
<div class="col-sm-8">
<!-- Blog Post-->
{% for obj in object_list %}
{% if obj.status == 'Published' %}
<article>
<div class="embed-responsive embed-responsive-16by9">
<img src="images/blog1.jpg" alt="" />
</div>
<div class="post-content">
<h2>{{obj.title}}</h2>
<div>
{{obj.created}} Author {{obj.user}}
<hr/>
<p>{{obj.body}}</p>
<a class="mtr-btn button-navy ripple" href= "{% url 'post_detail' slug= post.slug %}">Continue reading →</a><br>
</div>
</article>
{% endif %}
{% endfor %}
The view post_detail(request,slug=None) is to view details about a post. So your URL pattern is incorrect:
path('blog/post-detail/<slug:slug>',views.post_detail,name="post_detail"),
To call it in templates, the simpler and correct way to do is:
<a class="mtr-btn button-navy ripple" href= "{% url 'post_detail' obj.slug %}">Continue reading →</a><br>
</div>
#FOLLOW THIS PROCEDURE.I HOPE IT HELPS YOU OR ANY ONE ELSE IN THE FUTURE
# At blog/urls.py
from django.urls import path
from .views import (post_list, post_detail)
urlspatterns = [
path('blog/', post_list, name='post-list'),
path('<str:slug>/blog/post-detail/', post_detail, name='post-detail'),
]
#At blog/views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.objects.all()
template_name = blog/post_list.html
context = {'posts':posts}
return render(request, template_name, context)
def post_detail(request, slug):
posts = get_object_or_404(Post, slug=slug)
template_name = blog/post_detail.html
context = {'posts':posts}
return render(request, template_name, context)
# At the template/blog/post_list.html
{% block content %}
{% for post in posts %}
<article>
<div>
<small>{{ post.created_on|date:"F d, Y" }}</small>
<h2>{{ post.title }}</h2>
<p >{{ post.body }}</p>
</div>
</article>
{% endfor %}
{% endblock content %}
# At template/blog/post_detail.html
<article>
<div>
<small>{{ posts.created_on|date:"F d, Y" }}</small>
<h2>{{ posts.title }}</h2>
<p>{{ posts.body }}</p>
</div>
</article>
#The above code should fix the the issue properly.
If your a following Django 3 By Example Book can check this soltuion because I had the same problem.
Book teach how to create Post with a slug attribute with
models.SlugField and unique_for_date='pusblish' condition.
Then you add some posts from admin site.
Then you add some posts from admin site but then in admin.py book teach how to edit the register with
prepopulated_fields = {'sulg':('title',)}.
Finally, book teach you how to edit posts.
This is a problem because never
going to find a post created. So, the solution for me was delete
posts and the create new ones.
here my code:
models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
objects = models.Manager() # The default manager.
published = PublishedManager() # Our custom manager.
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.month,
self.publish.day, self.slug])
admin.py
from django.contrib import admin
from .models import Post
#admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'author', 'publish', 'status')
list_filter = ('status', 'created', 'publish', 'author')
search_fields = ('title', 'body')
prepopulated_fields = {'slug': ('title',)}
raw_id_fields = ('author',)
date_hierarchy = 'publish'
ordering = ('status', 'publish')
views.py
from django.shortcuts import render, get_object_or_404
# another views...
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request,
'blog/post/detail.html',
{'post': post})
blog/urls.py
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
# post views
path('', views.PostListView.as_view(), name='post_list'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/',
views.post_detail,
name='post_detail'),
]
my_site/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls', namespace='blog')),
]

Django blog posts not being returned

I am very new to Django and have been following through the blog tutorial from the book: "Django by Example."
The code below should return all blog posts with a status of "published" but it refuses to work. What appears to be the correct page loads up using the list.html code but there are no posts showing. I have double checked and I am creating posts with the admin site with the status set to "published." I am not sure if the problem is with the template, model, views or URLs so I am including it all here:
Models.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse
#Data model class for creating posts table enrties in database
#Custom manager. Limits returned querysets to ones with published status
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset()\
.filter(status='published') #super used to call get_queryset method from parent class as it is currently being
#overridden here.
class Post(models.Model):
STATUS_CHOICES = (('draft', 'Draft'), ('published', 'Published'),)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish') #A field for use in building urls
#slug = models.SlugField(slugify(title))
author = models.ForeignKey(User, related_name='blog_posts') #Each post written by a user and a user can write many posts
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
objects = models.Manager() #The default manager
published = PublishedManager() #Custom manager
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'),self.publish.strftime('%d'), self.slug])
views.py:
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request, 'blog/post/list.html', {'Posts': 'posts'})
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day)
return render(request, 'blog/post/detail.html', {'post':post})
URLs.py
from django.conf.urls import url
from . import views
urlpatterns = [
# post views
url(r'^$', views.post_list, name='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\
r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'),
Templates base.html:
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/blog.css" %}" rel="stylesheet">
</head>
<body>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="sidebar">
<h2>My Site site</h2>
<p>This site is all about me</p>
</div>
</body>
</html>
detail.html:
{% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
<h1>Blog</h1>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">Published{{ post.publish }} by {{ post.author }}</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% endblock %}
You need to use Post.published.all() to use your custom manager then in your dict you are doing 'Posts' with a capital P you might want to try lowercase as your view is using posts. Then also the value for it was a string instead of the variable posts. So something like this should work
def post_list(request):
posts = Post.published.all()
return render(request, 'blog/post/list.html', {'posts': posts})
You are passing in a string as your context object data:
return render(request, 'blog/post/list.html', {'Posts': 'posts'})
Needs to be
return render(request, 'blog/post/list.html', {'Posts': posts})
It also still isn't going to work since you have in your view and aren't calling the manager method. You have:
posts = Post.objects.all()
You need to use your customer manager.
I found the answer - all posts in the database are in the "draft" status, and status='published' is registered in the PublishedManager. Change status=''draft" and everything will be OK!

Categories

Resources