Simple search exercise from DjangoBook Chapter 7 - django

It seems to be working now, all I changed was chartext to charfield in my models. Why won't it search in chartext? Was that the fix?
I am having some issue with section 7 of djangobook, where we show the results of our book search. I am not using books, but I dont know what I am doing wrong.
Note: The search term 'q' is being passed through properly, it just wont show results. The template does show up though. I was going to just skip it, but I really am starting to wonder what else I could be doing wrong?
I am following from : http://djangobook.com/en/2.0/chapter07/ here is my code
urls.py
from django.conf.urls.defaults import patterns, include, url
from EM.catalog import views
urlpatterns = patterns('',
(r'^search-form/$', views.search_form),
(r'^search/$', views.search),
views.py
from django.template import loader, Context
from django.shortcuts import render_to_response
from django.http import HttpResponse
from EM.catalog.models import em_tank
def search_form(request):
return render_to_response('search_form.html')
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
tanknotes = em_tank.objects.filter(em_tank_notes__icontains=q)
return render_to_response('search-results.html', {'tanknotes': tanknotes, 'query': q})
else:
return HttpResponse("Please input a search term")
search-results.html
<p>You searched for: <strong>{{ query }}</strong></p>
{% if tanknotes %}
<p>Found {{ tanknotes|length }} result{{ tanknotes|pluralize }}.</p>
<ul>
{% for em_tank_notes in tanknotes %}
<li>{{ em_tank.em_tank_notes }}</li>
{% endfor %}
</ul>
{% else %}
<p>No tanks matched your search criteria.</p>
{% endif %}
models
from django.db import models
class em_tank(models.Model):
em_tank_date_acquired = models.DateField()
em_tank_notes = models.CharField(max_length=150, verbose_name='Notes', blank=True)

Related

I keep getting this error massage NoReverseMatch at /

I try to run this code but I get this error
NoReverseMatch at /
Reverse for 'all-posts' not found. 'all-posts' is not a valid view function or pattern name.
and I think my code is okay, here's a bit of it
My urls.py
from django.urls import path
from . import views
app_name = "blog"
urlpatterns = [
path("", views.index, name="home"),
path("all_posts", views.all_posts, name="all-posts"),
path("<str:tag>", views.sort_post, name="sorted")
]
here's my views.py
from django.shortcuts import render
from .models import Auhtor, Post, Caption
def index(request):
return render(request, "blog/index.html")
def all_posts(request):
all = Post.objects.all()
return render(request, "blog/all.html", {"all": all})
def sort_post(request, tag):
sort = Post.objects.filter(tag__caption=tag)
return render(request, "blog/sorted.html", {"sorted": sort})
and here's my all.html
{% extends "blog/base.html" %}
{% load static %}
{% block title %}
My Blog
{% endblock %}
{% block content %}
<div class="nav">
<ul>
All posts
</ul>
</div>
{% endblock %}

django.urls.exceptions.NoReverseMatch: Reverse for 'board_topics' with arguments '('',)' not found

i am struggling with this error, please any help,
i tried many solution for this error but nothing work
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse,Http404
from .models import Board
# Create your views here.
def home(request):
boards = Board.objects.all()
return render(request,'home.html',{'boards':boards})
def board_topics(request,board_id):
# try:
# board = Board.objects.get(pk=board_id)
# except:
# raise Http404
board = get_object_or_404(Board,pk=board_id)
return render(request,'topics.html',{'board':board})
def new_topic(request,board_id):
return render(request,'new_topic.html')
def about(request):
return HttpResponse(request,'yes')
url.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.home,name='home'),
path('about/',views.about,name='about'),
path('boards/<int:board_id>/', views.board_topics, name='board_topics'),
path('boards/<int:board_id>/new/', views.new_topic, name='new_topic')
]
new_topic.html
{% extends 'base.html' %}
{% block title %} creat new topic {% endblock %}
{% block breadcrumb %}
<li class="breadcrumb-item"> Boards </li>
<li class="breadcrumb-item"> {{board.name}} </li>
<li class="breadcrumb-item active">New Topic</li>
{% endblock %}
Usually I could easily read where the error is coming from and deal with it but in this case I can't spot the cause of the error hence I'm unable to progress with my study. Any help will be greatly appreciated.
You have to tell it what board_id is, since that's what you have in your URL.
<li class="breadcrumb-item"> {{board.name}} </li>

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

I am learning django framework and i am getting an error "
Reverse for 'results' not found. 'results' is not a valid view function or pattern name."
I am including my code here.
results.py:
{% extends "polls/base.html" %}
{% block main_content %}
<h1>{{question.question_text}}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{choice.choice_text}} -- {{choice.votes}} vote{{choice.votes|pluralize}}</li>
{% endfor %}
</ul>
Vote again
{% endblock%}
This is urls.py file of polls app.
urls.py:
from django.conf.urls import url
from . import views
urlpatterns=[
url(r"^$",views.index,name="index"), #127.0.0.1:8000/polls
url(r"^(?P<question_id>[0-9]+)/$",views.details,name="details"),
url(r"^(?P<question_id>[0-9]+)/results$",views.results,name="result"),
url(r"^(?P<question_id>[0-9]+)/vote$",views.vote,name="vote"),
]
views.py:
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
# from django.core.urlresolvers import reverse
from .models import Question
from django.urls import reverse
def results(request,question_id):
question=get_object_or_404(Question,pk=question_id)
return render(request,"polls/results.html",{"question":question})
def vote(request,question_id):
question=get_object_or_404(Question,pk=question_id)
try:
selected_choice=question.choice_set.get(pk=request.POST['choice'])
except:
return render(request,"polls/details.html",{'question':question,"error_message":"Please select a choice"})
else:
selected_choice.votes+=1
selected_choice.save()
return HttpResponseRedirect(reverse("polls:results",args=(question.id,)))
Change
return HttpResponseRedirect(reverse("polls:results",args=(question.id,)))
To
return HttpResponseRedirect(reverse("polls:result",args=(question.id,)))
Since it's defined in your urls.py as
url(r"^(?P<question_id>[0-9]+)/results$",views.results,name="result"),

Django Tutorial Page not found 404 [duplicate]

I was following the django documentation and making a simple poll app. I have come across the following error :
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, , didn't match any of these."
settings.py
ROOT_URLCONF = 'mysite.urls'
mysite/mysite/urls.py
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
url(r'^polls/',include('polls.urls')),
url(r'^admin/', admin.site.urls),]
mysite/polls/urls.py
from django.conf.urls import url
from . import views
app_name= 'polls'
urlpatterns=[
url(r'^$',views.IndexView.as_view(),name='index'),
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$',views.ResultsView.as_view(),name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'),]
mysite/polls/views.py
from django.shortcuts import get_object_or_404,render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from django.template import loader
from .models import Choice,Question
from django.template.loader import get_template
#def index(request):
# return HttpResponse("Hello, world. You're at the polls index")
class IndexView(generic.ListView):
template_name='polls/index.html'
context_object_name='latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[5:]
class DetailView(generic.DetailView):
model=Question
template_name='polls/detail.html'
def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
return Question.objects.filter(pub_date__lte=timezone.now())
class ResultsView(generic.DetailView):
model= Question
template_name ='polls/results.html'
def vote(request, question_id):
question=get_object_or_404(Question, pk=question_id)
try:
selected_choice= question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/details.html',
{
'question':question,
'error_message' : "You didn't select a choice" ,
})
else:
selected_choice.votes+=1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
index.html
<!DOCTYPE HTML >
{% load staticfiles %}
<html>
<body>
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{question.question_test }}
</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
This link http://127.0.0.1:8000/polls/ shows a blank page with 3 bullets. (I have 3 questions in my database and their id's are 5,6,7 because I have been deleting and adding the questions.)
My admin works fine!
I'm new to Django and have been searching and asking around and have been stuck on it for a while now.
You get the 404 on http://127.0.0.1:8000/ because you have not created any URL patterns for that url. You have included the url http://127.0.0.1:8000/polls/, because you have included the polls urls with
url(r'^polls/',include('polls.urls')),
The empty bullets suggest that there is a problem with your polls/index.html template. It looks like you have a typo and have put {{ question.question_test }} instead of {{ question.question_text }}. Make sure that it exactly matches the template from the tutorial 3:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Make sure there is no typo in your code. Putting space between inverted commas can also lead to this error. Just make sure you have put path('',include('home.urls')) and not path(' ',include('home.urls'))
Note: here home.urls is the name of my app in Django

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/

I was following the django documentation and making a simple poll app. I have come across the following error :
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, , didn't match any of these."
settings.py
ROOT_URLCONF = 'mysite.urls'
mysite/mysite/urls.py
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
url(r'^polls/',include('polls.urls')),
url(r'^admin/', admin.site.urls),]
mysite/polls/urls.py
from django.conf.urls import url
from . import views
app_name= 'polls'
urlpatterns=[
url(r'^$',views.IndexView.as_view(),name='index'),
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$',views.ResultsView.as_view(),name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'),]
mysite/polls/views.py
from django.shortcuts import get_object_or_404,render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from django.template import loader
from .models import Choice,Question
from django.template.loader import get_template
#def index(request):
# return HttpResponse("Hello, world. You're at the polls index")
class IndexView(generic.ListView):
template_name='polls/index.html'
context_object_name='latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[5:]
class DetailView(generic.DetailView):
model=Question
template_name='polls/detail.html'
def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
return Question.objects.filter(pub_date__lte=timezone.now())
class ResultsView(generic.DetailView):
model= Question
template_name ='polls/results.html'
def vote(request, question_id):
question=get_object_or_404(Question, pk=question_id)
try:
selected_choice= question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/details.html',
{
'question':question,
'error_message' : "You didn't select a choice" ,
})
else:
selected_choice.votes+=1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
index.html
<!DOCTYPE HTML >
{% load staticfiles %}
<html>
<body>
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{question.question_test }}
</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
This link http://127.0.0.1:8000/polls/ shows a blank page with 3 bullets. (I have 3 questions in my database and their id's are 5,6,7 because I have been deleting and adding the questions.)
My admin works fine!
I'm new to Django and have been searching and asking around and have been stuck on it for a while now.
You get the 404 on http://127.0.0.1:8000/ because you have not created any URL patterns for that url. You have included the url http://127.0.0.1:8000/polls/, because you have included the polls urls with
url(r'^polls/',include('polls.urls')),
The empty bullets suggest that there is a problem with your polls/index.html template. It looks like you have a typo and have put {{ question.question_test }} instead of {{ question.question_text }}. Make sure that it exactly matches the template from the tutorial 3:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Make sure there is no typo in your code. Putting space between inverted commas can also lead to this error. Just make sure you have put path('',include('home.urls')) and not path(' ',include('home.urls'))
Note: here home.urls is the name of my app in Django