I am new to python and django and I was following a tut with major errata. right now I am trying to get the results page to display my results. This is not my code, it's from a tutorial. Here is my code.
my views.py
def post_search(request):
form = request.GET.get('q')
results = SearchQuerySet().models(Post).filter(content=form)
# count total results
total_results = results.count()
template = 'blog/post/search.html',
context = {
'form': form,
'results': results,
'total_results': total_results
}
return render(request, template, context)
my search.html
{% extends "blog/base.html" %}
{% block title %}Search{% endblock %}
{% block content %}
{% if request.GET %}
<h1>Posts containing "{{ form.query }}"</h1>
<h3>Found {{ total_results }} result{{ total_results|pluralize}}</h3>
{% for result in results %}
{% with post=result.object %}
<h4>{{ post.title }}</h4>
{{ post.body|truncatewords:5 }}
{% endwith %}
{% empty %}
<p>There are no results for your query.</p>
{% endfor %}
<p>Search again</p>
{% else %}
<h1>Search for posts</h1>
<form action="." method="get">
<div>
<div class="input-group">
<input type="text" class="form-control" autocomplete="off" name="q" id="search" placeholder="search" value="{{ request.GET.q }}">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">search</button>
</span>
</div><!-- /input-group -->
<ul class="list-group" id="search-results" style="margin: 5px 0 0 0; width: 325px">
</ul>
</div>
</form>
{% endif %}
{% endblock content%}
my post_text.txt
{{ object.title }}
{{ object.tags.all|join:", " }}
{{ object.body }}
search_indexes.py
from haystack import indexes
from .models import Post
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
publish = indexes.DateTimeField(model_attr='publish')
# title_auto = indexes.EdgeNgramField(model_attr='title')
# content_auto = indexes.EdgeNgramField(model_attr='content')
def get_model(self):
return Post
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.all()
the only thing that shows on the page after I run a search is
Posts containing ""
Found 1 result
Search again
and if I do this
{{results}}
it returns this
[<SearchResult: blog.post (pk='2')>]
where it says post containing a name will show
found results returns a number which lets me know that the results are working
any and all help or guidance in the right direction is greatful. Tried to read the docs. They seem so vague to me. and as I said I am a novice.and there are only video on the topic and that with frank hibbert and he uses it with ajax
Related
The books are being displayed but when i click on the link it does not lead to the google books.co.in webpage where the book is stored, it displays that the page is not found.
my views.py
def books(request):
if request.method == "POST":
form=DashboardForm(request.POST)
text=request.POST['text']
url="https://www.googleapis.com/books/v1/volumes?q="+text
r = requests.get(url)
answer = r.json()
result_list = []
for i in range(10):
result_dict = {
'title':answer['items'][i]['volumeInfo']['title'],
'subtitle':answer['items'][i]['volumeInfo'].get('subtitle'),
'description':answer['items'][i]['volumeInfo'].get('description'),
'count':answer['items'][i]['volumeInfo'].get('pageCount'),
'categories':answer['items'][i]['volumeInfo'].get('categories'),
'rating':answer['items'][i]['volumeInfo'].get('pageRating'),
'thumbnail':answer['items'][i]['volumeInfo'].get('imageLinks').get('thumbnail'),
'preview':answer['items'][i]['volumeInfo'].get('previewLinks')
}
result_list.append(result_dict)
context={
'form' : form,
'results' :result_list
}
return render(request,'dashboard/books.html',context)
else:
form=DashboardForm()
context={'form' : form}
return render(request,'dashboard/books.html',context)
my books.html template
{% extends 'dashboard/base.html' %}
{% load static %}
{% block content %}
<section class='text-center container'>
<h2><b>SEARCH FOR BOOKS </b></h2>
<p>Enter the search query to obtain your desired book</p><b></b>
<form action="" method="post">
{% csrf_token %}
{{form}}
<input class="btn btn-danger" type="submit" value="Submit">
</form><br>
{% for result in results %}
<a href="{{result.preview}}" target="_blank">
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-md-3">
<img class="img-fluid" src="{{result.thumbnail}}" alt="">
</div>
<div class="col-md-9">
<h3 class="p-0 m-0">{{result.title}}</h3>
<b>
<u>
<h5 class="p-0 m-0">{{result.subtitle}}</h5>
</u>
</b>
{% if result.description %}
<h6 class="p-0 m-1">{{result.description}}</h6>
{% endif %}
<b>
{% if result.categories %}
<h6 class="ml-0 mt-3">Category:
{% for category in result.categories %}
{{category}}
{% endfor %}
</h6>
{% endif %}
{% if result.count %}
<h6 class="ml-0 mt-1">Pages: {{result.count}}</h6>
{% endif %}
{% if result.rating %}
<h6 class="ml-0 mt-1">Rating:{{result.rating}}</h6>
{% endif %}
</b>
</div>
</div>
</div>
</div>
</a>
{% endfor %}
<br>
</section>
{% endblock content %}
I have installed and imported requests and want to redirect to google books page when i click on the book.
enter image description here
The issue seems to be with the value of "preview" in the "result_dict" dictionary. It looks like the "previewLinks" key in the JSON response from the Google Books API does not contain a URL that can be directly accessed.
You can try it like this:
result_dict = {
...
'preview': answer['items'][I]['volumeInfo'].get('previewLinks').get('googlePlay'),
...
}
Hi i am trying to create a search engine and i need to make the table id stay in the link.
In my CrawledTables have all the tables with the id...and i need to pass that id into the var pk through the links...cause then i request to get that pk and use the pk to get the table name. and then use the table name to get the data inside the table i searched for...and make a search engine inside those table info.
Error:
Reverse for 'table_search' with no arguments not found. 1 pattern(s) tried: [u'search/(?P<pk>\\d+)/$']
This is my views.py
def search_form(request):
return render(request, 'search/search.html')
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
name = Crawledtables.objects.filter(name__icontains=q)
return render(request, 'search/results.html', {'name': name, 'query': q})
else:
return HttpResponse('Please submit a search term.')
def search_form_table(request):
return render(request, 'search/search_table.html', {'tbl_nm': table_name})
def search_table(request, pk):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
table_name = Crawledtables.objects.get(id=pk)
print table_name
t = create_model(table_name.name)
print t
title = t.objects.filter(title__icontains=q)
print title
return render(request, 'search/results_table.html', {'tbl_name': table_name,
'details': title,
'query': q})
else:
return HttpResponse("Please submit a search term!")
this is my search/urls.py
urlpatterns = [
url(r'^results$', views.search, name='search'),
url(r'^$', views.search_form, name='form'),
url(r'^(?P<pk>\d+)/$', views.search_form_table, name='table_search'),
url(r'^(?P<pk>\d+)/results$', views.search_table, name='table_results'),
]
this is my search.html
<form action="/search/results" method="GET">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
results.html
<p> You searched for: <strong>{{ query }}</strong></p>
{% if name %}
<p> Found {{ name|length }}</p>
<ul>
{% for nm in name %}
<li>{{ nm.name }} {{ nm.date }}</li>
{% endfor %}
</ul>
{% else %}
<p> No results found</p>
{% endif %}
search_table.html
<form action="/search/{{ pk }}/results" method="GET">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
results_table.html
<p> You searched for: <strong>{{ query }}</strong></p>
{% if details %}
<p> Found {{ details|length }}</p>
<ul>
{% for list in details %}
<li> {{ list.title }}</li>
{% endfor %}
</ul>
{% else %}
<p> No results found</p>
{% endif %}
You are getting the error because of <a href="{% url 'search:table_search' %}"> in your results.html. Change the href like this.
{% for nm in name %}
<li>{{ nm.name }} {{ nm.date }}</li>
{% endfor %}
I am writing an application with django. everything has been working fine and I have been working in another page of the application then I decided to come back to the home page and I got this error.
Reverse for 'more' with keyword arguments '{u'slug': u''}' not found. 1 pattern(s) tried: ['(?P<slug>[-\\w]+)/$']
Everything was working perfectly and I cant seen to understand why.
If I change the template to another template lets say hello.html the whole url responds well but once I change it back to index.html I get that same error. any help would be appreciated
form.py
from django import forms
from posts.models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
"title",
"content",
"image",
"draft",
"publish",
]
views.py
def index(request):
results = Post.objects.all().filter(draft=False).filter(publish__lte=timezone.now())
que = request.GET.get("q")
if que:
results =results.filter(
Q(title__icontains=que)|
Q(content__icontains=que)).distinct()
paginator = Paginator(results, 8) # Show 25 contacts per page
pages ="page"
page = request.GET.get('page')
try:
query = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
query = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
query = paginator.page(paginator.num_pages)
context = {
"objects": query,
"pages": pages
}
template = 'index2.html'
return render(request,template,context)
html
{% extends 'base.html' %}
{% load staticfiles %}
{% block content %}
<h1>This is Home</h1>
{% include 'messages.html'%}
<form method="GET" action="">
{% csrf_token %}
<input type="text" name="q" value="{{ request.GET.q }}" placeholder="search" >
<input type="submit" name="submit" value="Go!">
</form>
{% for obj in objects %}
<h1> {{ obj.title }}</h1><br>
{% if obj.image %}
<img src="{{ obj.image.url }}" alt="{{ obj.title }}" width="250" height="250"><br>
{% endif %}
{{ obj.content|safe|truncatewords:20 }}
{{ obj.timestamp }}<br>
{{ obj.updated }}<br>
{% endfor %}
<br>
<div class="pagination">
<span class="step-links">
{% if contacts.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ objects.number }} of {{ objects.paginator.num_pages }}.
</span>
{% if objects.has_next %}
next
{% endif %}
</span>
</div>
{% endblock %}
Absolute url in model
def get_absolute_url(self):
return reverse("more", kwargs={"slug": self.slug})
url pattern
url(r'^$', posts_views.index, name='index'),
I am trying to create a form in Django with the form wizard where there are multiple (repeating) formsets in the same step of the wizard.
What I have is:
# forms.py
class FormStep1A(forms.Form):
answerA = forms.CharField(max_length=100)
remarkA = forms.CharField(widget=forms.Textarea)
class FormStep1B(forms.Form):
answerB = forms.CharField(max_length=100)
remarkB = forms.CharField(widget=forms.Textarea)
class FormStep1(forms.Form):
partA = formset_factory(FormStep1A)
partB = formset_factory(FormStep1B)
and
# urls.py
STEPS = (
('1', FormStep1),
# ...
)
# FormWizard is a subclass of NamedUrlSessionWizardView
wizard = FormWizard.as_view(STEPS, url_name='form_new_step')
urlpatterns = patterns(
'',
url(r'^new/(?P<step>.+)/$', wizard,
name='form_new_step'),
url(r'^new/$', wizard, name='form_new'),
)
And my template looks the same as in the documentation. However, my form is rendered empty with no fields at all.
I know there are similar questions or recipes out there:
Django formwizard with formsets and forms on same page
django wizard, using form and formset in the same step
Combining a Form and a FormSet in Django: How to pass them in the context?
But I just cannot get this to work. Any help is much appreciated, thank you!
UPDATE: My template looks like this:
{% extends 'base.html' %}
{% load i18n %}
{% block head %}
{{ wizard.form.media }}
{% endblock %}
{% block content %}
<div class="row">
<div class="large-12 columns">
<h3>{% trans "Questionnaire" %}</h3>
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form action="" method="post">
{% csrf_token %}
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
{% if wizard.steps.prev %}
<button class="button tiny" name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "First step" %}</button>
<button class="button tiny" name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "Prev step" %}</button>
{% endif %}
<input class="button tiny" type="submit" value="{% trans "Submit" %}"/>
</form>
</div>
</div>
{% endblock %}
I have a single HTML page with 2 Django Forms in it, all in the same <form>..</form> tag. Everything works great, except when I try to upload multiple files.
Each form has their own image, and for some reason I can only save the image from the first form. Other data from the second form still gets saved, but without any image. I don't see any errors or exception raised, so I don't know what's going wrong :s.
Here's my views.py
def display_form(request):
if request.method == 'POST':
form_team = TeamForm(request.POST, request.FILES, prefix="team")
form_player = PlayerForm(request.POST, request.FILES, prefix="play")
#form_ketua = KetuaForm(request.POST, request.FILES, prefix="ketua")
if all([form.is_valid() for form in [form_team, form_player]]):
# save Team data first, overwrite if exists
try:
team = Team.objects.get(kota=form_Team.cleaned_data['name'])
team.profil = form_Team.cleaned_data['profil']
team.save()
except Team.DoesNotExist:
team = Team(**form_Team.cleaned_data)
team.save()
play = form_Player.save(commit=False)
play.name = team
play.save()
else:
form_team = TeamForm(prefix="team")
form_player = PlayerForm(prefix="play")
#form_ketua = KetuaForm(prefix="ketua")
print "a"
# list with tuple (form, legend) to pass as context
forms = [(form_Team, 'Team Data'),
(form_Player, 'Player Profile'),
]
return render_to_response(
'form/team.html',
{
'formlist': forms,
},
)
What am I doing wrong?
EDIT: Here's my template
{% extends "base.html" %}
{% block title %}Form - {{ title }}{% endblock %}
{% block content %}
<form action="." method="POST" enctype="multipart/form-data">{% csrf_token %}
{% for formitem in formlist %}
{% if formitem.1 %}
<fieldset>
<legend>{{ formitem.1 }}</legend>
{% endif %}
{{ formitem.0.non_field_errors }}
{% for field in formitem.0.visible_fields %}
<div class="formfield">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
{% if formitem.1 %}
</fieldset>
{% endif %}
{% endfor %}
<div id="formbuttons">
<input type="submit" value="Submit" class="button">
<input type="reset" value="Reset" class="button">
</div>
</form>
{% endblock %}
looks like you are missing a play.save() (you save the form with commit=False)