No Post matches the given query - django

I am using Django version 2.
I am working on a blog web app using PostgreSQL database.
I am trying to add a search feature to the web app but when I open the url (http://localhost:8000/search/) to make a search, I get the error below.
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/search/
Raised by: blog.views.post_detail
No Post matches the given query.
here is the blog/urls.py
from django.contrib.postgres.search import SearchVector
from .forms import CommentForm, SearchForm
from .models import Post, Comment
from django.shortcuts import render, get_object_or_404
from django.urls import path
from . import views
urlpatterns = [
path('', views.PostListView.as_view(), name='home'),
path('<slug:post>/', views.post_detail, name='post_detail'),
path('<int:post_id>/share', views.post_share, name='share'),
path('search/', views.post_search, name='post_search'),
]
here is the views.py
def post_detail(request, post):
post = get_object_or_404(Post, slug=post)
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
return render(request, 'detail.html', {'post': post,
'comments': comments, 'new_comment':
new_comment,'comment_form': comment_form})
def post_search(request):
form = SearchForm()
query = None
results = []
if 'query' in request.GET:
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']
results = Post.objects.annotate(
search=SearchVector('title','body'),
).filter(search=query)
return render(request, 'search.html',
{'form':form,'query':query,'results':results})
Here are the templates files.
For search.html -(page to make query)
{% extends 'base.html' %}
{% block title %}Search{% endblock title %}
{% block page_title %}Search Posts{% endblock page_title %}
{% block content %}
{% if query %}
<h1>Posts containing "{{ query }}"</h1>
<h3>
{% with results.count as total_results %}
Found {{ total_results }} result{{ total_results|pluralize }}
{% endwith %}
</h3>
{% for post in results %}
<h4>{{ post.title }}</h4>
{{ post.body|truncatewords:5 }}
{% empty %}
<p>There is no results for your query.</p>
{% endfor %}
<p>Search again</p>
{% else %}
<h1>Search for posts</h1>
<form action="." method="GET">
{{ form.as_p }}
<input type="submit" value="Search">
</form>
{% endif %}
{% endblock content %}
For the html for post_detail
{% extends 'base.html' %}
{% load blog_tags %}
{% load crispy_forms_tags %}
{% load profanity %}
{% block title %}{{post.title}}{% endblock title %}
{% block navlink %}
<nav>
<ul>
<li class="current">Home</li>
<li>About</li>
<li >Services</li>
</ul>
</nav>
{% endblock navlink %}
{% block page_title %}{{post.title}}{% endblock page_title %}
{% block content %}
{{post.body|markdown}}
<p>Share this post via email</p>
{% with comments.count as total_comments %}
<h2>{{ total_comments }} comment{{ total_comments|pluralize }} </h2>
{% endwith %}
<div class="container">
{% for comment in comments %}
<div class="comment">
<p>Comment {{ forloop.counter }} by <em>{{ comment.name }}</em> - {{comment.created}} </p>
{{ comment.body|censor|linebreaks }}
</div>
{% empty %}
<p>There are no comments yet.</p>
{% endfor %}
{% if new_comment %}
<h2>Your comment has been added</h2>
{% else %}
<h2>Add a new comment</h2>
<form method="post">{% csrf_token %}
{{comment_form|crispy}}
<input class="button_1" type="submit" value="Add comment">
</form>
{% endif %}
</div>
{% endblock content %}

This is probably for one of the strange reason search is here actually matches with slug:post. One of easiest solution for your problem is to re-order urls and make sure /search place before. Like following
urlpatterns = [
path('', views.PostListView.as_view(), name='home'),
path('search/', views.post_search, name='post_search'),
path('<slug:post>/', views.post_detail, name='post_detail'),
path('<int:post_id>/share', views.post_share, name='share')
]
My suggestion for further developement whenever its need to add slug in url we need to make sure there is some prefix before it.

Related

Reverse for 'about_me' not found. 'about_me' is not a valid view function or pattern name

What's happening. I still have trouble displaying the title list. Where did I make a mistake?
views.py
def dashboard(request):
bookmarks = Text_field.objects.order_by('created')
return render(request, 'Site/dashboard.html', {'bookmarks': bookmarks})
def about_me(request, pk):
about = get_object_or_404(Text_field, pk=pk)
return render(request, 'Site/about_me.html', {'about': about})
dashboard.html
{% extends "Site/base.html" %}
{% load static %}
{% block content %}
{% for bookmark in bookmarks %}
<div>
<p>Stworzono dn. {{ bookmark.created }}</p>
<h1>{{ bookmark.title }}</h1>
<p>{{ bookmark.text|linebreaksbr }}</p>
</div>
{% endfor %}
{% endblock %}
urls.py
path('', views.dashboard, name='dashboard'),
path('about/<int:pk>/', views.about_me, name='about_me'),
In your comment you say you defined an app_name in your urls.py, you need to include that app_name in your {% url ... %} name:
{% url 'Site:about_me' pk=bookmark.pk %}

printing db values to html django

can anyone help?
I want to print some counts from the DB (total records where the complete field = true and another when it equals false.
What have I done wrong in the below?
Thanks
VIEWS
def task_count(request):
completetasks = Todo.objects.filter(complete=True).count()
incompletetasks = Todo.objects.filter(complete=False).count()
return render(request, 'counts.html')
URLS
urlpatterns = [
url(r'^$', views.todo, name='index'),
url(r'^create/$', views.create_task, name='create'),
url(r'^counts/$', views.task_count, name='counts'),
COUNTS.HTML
{% extends 'base.html' %}
{% block content %}
<br><br><br>
{% if user.is_authenticated %}
<div class="container">
{% filter upper %}
<h3>Notes for task</h3>
{% endfilter %}
</div>
{{ completetasks }}
{% else %}
<h2>Login</h2>
{% endif %}
{% endblock %}
In your views file change like this
def task_count(request):
completetasks = Todo.objects.filter(complete=True).count()
incompletetasks = Todo.objects.filter(complete=False).count()
context = {
'completetasks': completetasks,
'incompletetasks': incompletetasks
}
return render(request, 'counts.html', context)
Then in counts.html
{{ completetasks }}
{{ incompletetasks }}

Deleting object from a view in Django

I have a page that shows a list of objects and I want to add a button beside each one to enable the user to delete it. I've found a few questions about similar scenarios online but for some reason I keep getting errors when I try to replicate the solutions.
Here is the delete function in views.py:
def delete_dish(request, pk):
query = Dish.objects.get_object_or_404(pk)
supermenu = query['supermenu'].pk
query.delete()
return redirect('foodmenu:menu', supermenu)
Here is the form in the HTML template:
{% if not supermenu.dish_set.count == 0 %}
<ul>
{% for dish in supermenu.dish_set.all %}
<li>
{{ dish.name }} - {{ dish.description }}
<form action="{% url 'foodmenu:delete_dish' dish.id %}" method="POST">
{% csrf_token %}
<button type="submit">X</button>
</form>
</li>
{% if not dish.price_set.count == 0 %}
<ul>
{% for price in dish.price_set.all %}
{% if price.label %}
<li>{{ price.label }}: {{ price.cost }}</li>
{% else %}
<li>{{ price.cost }}</li>
{% endif %}
{% endfor %}
</ul>
{% endif %}
{% endfor %}
</ul>
{% else %}
<p>No dishes on this menu!</p>
{% endif %}
And here is the urls.py:
app_name = 'foodmenu'
urlpatterns = [
...
path('dish/delete/<int:dish.id>', views.delete_dish, name="delete_dish")
]
When I click the button, the browser goes to ./dish/delete/1 (1 being the pk of the object), but Django returns a 404 error.
Instead of query = Dish.objects.get_object_or_404(pk) you should use get_object_or_404 shortcut:
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_POST
#require_POST
def delete_dish(request, pk):
if request.method
query = get_object_or_404(Dish, pk=pk)
supermenu = query.supermenu.pk
query.delete()
return redirect('foodmenu:menu', supermenu)
Also change your url pattern to this:
path('dish/delete/<int:pk>/', views.delete_dish, name="delete_dish")
UPD
As #daniherrera mentioned in his comment, you probably want to check request's method, to prevent accidental deletions. For this you can use require_POST decorator.

How to GET data by search word Django

I have problem getting the data to the home page.
I would like to filter out all the books based on Genre. I'm following the
MDN site for this.
index.html
{% extends "base_generic.html" %}
{% block content %}
<h1>Local Library Home</h1>
<p>Welcome to <em>Local Library</em>, a very basic Django website.</p>
<h2>Dynamic content</h2>
<form action="" method="get">
<input type="text" name="genre" placeholder="Search">
<input type="submit" value="Search">
</form>
{% endblock %}
urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^books/$', views.BookListView.as_view(), name='books'),
url(r'^(?P<string>[-\w]+)$', views.GenreListView.as_view(), name='index'),
]
GenreListView class
class GenreListView(generic.ListView):
model = Book
def get(request, string):
try:
book = Book.objects.all().filter(genre=string)
except Book.DoesNotExist:
raise Http404("Book does not exist")
return render(
request,
'index.html',
context={'book': book,}
)
I can't figure out what I'm missing or what else I have to do to get all the date based on genre?
EDIT:
whole index.html
{% extends "base_generic.html" %}
{% block content %}
<h1> Book List </h1>
<form action="" method="get">
<input type="text" name="genre" placeholder="Search">
<input type="submit" value="Search">
</form>
{% if book_list %}
<ul>
{% for book in book_list %}
<li>
{{ book.title }} ({{ book.author }})
</li>
{% endfor %}
</ul>
{% else %}
<p>There are no books in the library</p>
{% endif %}
{% endblock %}
You should override get_queryset, No need to rewrite get
class GenreListView(generic.ListView):
model = Book
template_name = 'index.html'
def get_queryset(self):
books = Book.objects.all()
query = self.request.GET.get('genre', None)
if query:
return books.filter(genre=query)
return books
The exception Book.DoesNotExist will never
occur if you filter() queryset. it will always return a empty queryset in case of no object found

Django http404 error urlconf confusion

I was really confused why I was receiving Http404 error. To be more clear heres my code:
My app named books
views.py
from django.shortcuts import render_to_response
from django.http import Http404
from django.template import RequestContext
from books.models import *
def index(request):
title = 'Book Gallery'
books = Book.objects.all().order_by('-id')
lang_list = Lang.objects.all().order_by('-lang')
template = 'books/index.djhtml'
context = {'books': books, 'title': title, 'lang_list': lang_list}
return render_to_response( template, context, context_instance=RequestContext(request) )
def by_book_slug(request, bookslug):
slug = bookslug
try:
book = Book.objects.get(slug=slug)
except:
raise Http404
title = book.name
template = 'books/singlebook.djhtml'
context = {'book': book, 'title': title}
return render_to_response( template, context, context_instance=RequestContext(request) )
def by_lang_slug(request, langslug):
filter = langslug
try:
language = Lang.objects.get(slug=filter)
except:
raise Http404
lang_list = Lang.objects.all().order_by('-lang')
books = Book.objects.filter(lang=language).order_by('-id')
title = language
template = 'books/by_language.djhtml'
context = {'books': books, 'title': title, 'filter': filter, 'lang_list': lang_list}
return render_to_response( template, context, context_instance=RequestContext(request) )
urls.py inside my book app folder
from django.conf.urls import patterns, include, url
from books import views
urlpatterns = patterns('',
url(r'(?P<langslug>.*)/$', views.by_lang_slug, name='by_lang'),
url(r'(?P<bookslug>.*)/$', views.by_book_slug, name='by_book'),
url(r'^$', views.index, name='book_gallery'),
)
link that pertains to langslug url conf works but those links for bookslug url conf does not work. When I try to switch them down and up, one of them work and the other one is not.
I really don't know what is happening here. Any help will be a great help. Thanks.
the index template of my books app
{% extends 'base.djhtml' %}
{% block title %} | Gallery{% endblock %}
{% block stylesheets %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
{% endblock %}
{% block content_header %}
{% endblock %}
{% block content_body %}
<div class="row">
<div class="span3">
<strong>filtered by >
{% if filter %}
{{ filter }}
{% else %}
All
{% endif %}
</strong>
<ul class="nav nav-list">
<li class="nav-header">Filter</li>
<li class="nav-header
{% if not filter %}
active
{% endif %}
">All</li>
{% for list in lang_list %}
<li class="nav-header
{% if filter == list.slug %}
active
{% endif %}
">
{{ list.lang }}
</li>
{% endfor %}
</ul>
</div>
<div class="span9">
{% for book in books %}
<div class="span3">
<a href="{{ book.book_cover.url }}">
<img alt="{{book.name}}" src="{{ book.thumbnail.url }}" />
</a>
<h4>{{book.name}}</h4>
<p>{{book.desc|truncatewords:15}}</p>
View more...
</div>
{% endfor %}
</div>
</div>
{% endblock %}
The by_language template for my book app
{% extends 'base.djhtml' %}
{% block title %} | Gallery{% endblock %}
{% block stylesheets %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
{% endblock %}
{% block content_header %}
{% endblock %}
{% block content_body %}
<div class="row">
<div class="span3">
<strong>filtered by >
{% if filter %}
{{ filter }}
{% else %}
All
{% endif %}
</strong>
<ul class="nav nav-list">
<li class="nav-header">Filter</li>
<li class="nav-header
{% if not filter %}
active
{% endif %}
">All</li>
{% for list in lang_list %}
<li class="nav-header
{% if filter == list.slug %}
active
{% endif %}
">
{{ list.lang }}
</li>
{% endfor %}
</ul>
</div>
<div class="span9">
{% for book in books %}
<div class="span3">
<a href="{{ book.book_cover.url }}">
<img alt="{{book.name}}" src="{{ book.thumbnail.url }}" />
</a>
<h4>{{book.name}}</h4>
<p>{{book.desc|truncatewords:15}}</p>
View more...
</div>
{% endfor %}
</div>
</div>
{% endblock %}
I have included a raise Http404 method when specified slug does not match to any query in the database. The thing I was confused about is, when I try to switch langslug and bookslug urlconf, links that are associated to one of these url works and the other is not.
Based on your url, if I put value on it even though they have different view, the result would be:
urlpatterns = patterns('',
# http://localhost:8000/English/
url(r'(?P<langslug>.*)/$', views.by_lang_slug, name='by_lang'),
# http://localhost:8000/YourBook/
url(r'(?P<bookslug>.*)/$', views.by_book_slug, name='by_book'),
# http://localhost:8000/
url(r'^$', views.index, name='book_gallery'),
)
Have you notice it, they have the same pattern so the first view execute is the by_lang_slug. So if you change the order the other one will be executed first. The best thing to do about it is to have a unique url name.
urlpatterns = patterns('',
# http://localhost:8000/lang/English/
url(r'lang/(?P<langslug>.*)/$', views.by_lang_slug, name='by_lang'),
# http://localhost:8000/book/YourBook/
url(r'book/(?P<bookslug>.*)/$', views.by_book_slug, name='by_book'),
# http://localhost:8000/
url(r'^$', views.index, name='book_gallery'),
)
Now they are different....