Making search bar in django - python

Im trying to make a search bar in django and watched several youtube totorials and none of those worked. What im trying to do is either make a search bar that redirects to articles/what_you_searched_for or if not possible show up results that include search. If someone has enough time they can tell me how to do both :).
in views.py:
def index(request):
queryset = article.objects.all()
number_of_records = article.objects.count()
random_page = random.randint(1,number_of_records)
context = {
"object_list": queryset,
"random_page": random_page
}
# query = ""
# if request.GET:
# query = request.GET['q']
# context['query'] = str(query)
entries = util.list_entries()
return render(request, "encyclopedia/index.html", context)
#{
#"entries": util.list_entries(),
#"random_page": random_page,
#})
def dynamic_articles_view(request, my_id):
obj = article.objects.get(id= my_id)
number_of_records = article.objects.count()
random_page = random.randint(1,number_of_records)
context = {
"object": obj,
"random_page": random_page
}
return render(request, "encyclopedia/article_detail.html", context)
in index.html:
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia
{% endblock %}
{% block body %}
<h1 id="demo" onclick="add_article()">Article</h1>
<ul>
{% for instance in object_list %}
<li>{{instance.title}}</li>
{% endfor %}
</ul>
{% endblock %}
layout.html: ------------ SEARCH BAR HERE ---------
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
</head>
<body>
<div class="row">
<div class="sidebar col-lg-2 col-md-3">
<h2>Wiki</h2>
<form action = "/articles/{{q}}"> __________EXACTLY HERE ________
<input class="search" type="text" name="q" placeholder="Search...">
</form>
<div>
Home
</div>
<div>
<a href = "/new_article" >Create New Article</a>
</div>
<div>
Random Page
</div>
{% block nav %}
{% endblock %}
</div>
<div class="main col-lg-10 col-md-9">
{% block body %}
{% endblock %}
</div>
</div>
</body>
</html>
urls:
from django.contrib import admin
from django.urls import include, path
from encyclopedia import views
from encyclopedia.views import index, new_article, dynamic_articles_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("encyclopedia.urls")),
path('new_article/', new_article),
path('home/', index, name = 'home'),
path('articles/<int:my_id>/', dynamic_articles_view, name = 'articless')
]
encyclopedia urls (other folder):
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("", views.new_article, name="new_article")
]
if needed i will comment models and forms but i dont want to make my question to long.

Simplest way is to add a GET form in your template with a search input without setting the action of the form:
<form action="">
<input type="text" name="search" placeholder="Search by title" value="{{request.GET.title}}">
<input type="submit" value="Search">
</form>
Then in the views.py in the you get the value. If it's given, you filter by it:
def dynamic_articles_view(request):
context['object_list'] = article.objects.filter(title__icontains=request.GET.get('search'))
return render(request, "encyclopedia/article_detail.html", context)

Related

(NoReverseMatch at / Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['<int:id>/']). please help me to remove this error

It is a multiple image program in which we can add multiple image at one time to see grouped photos. Error during template rendering
In template C:\Users\a\dev\mysite\templates\base.html, error at line 15
I am able to open my admin panel but i am not able to my files. thus please help me to find error:
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
image = models.ImageField(upload_to='products/', null=True, blank=True)
def __str__(self):
return self.title
class PostImage(models.Model):
post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to='images/')
def __str__(self):
return self.post.title
views.py
from django.shortcuts import render, get_object_or_404
from .models import Post, PostImage
def blog_view(request):
posts = Post.objects.all()
return render(request, 'blog.html', {'posts':posts})
def detail_view(request, id):
post = get_object_or_404(Post, id=id)
photos = PostImage.objects.filter(post=post)
return render(request, 'detail.html', {
'post':post,
'photos':photos,
})
admin.py
from django.contrib import admin
from .models import Post, PostImage
class PostImageAdmin(admin.StackedInline):
model=PostImage
#admin.register(Post)
class PostAdmin(admin.ModelAdmin):
inlines = [PostImageAdmin]
class Meta:
model=Post
#admin.register(PostImage)
class PostImageAdmin(admin.ModelAdmin):
pass
base.html
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css" integrity="sha384-DhY6onE6f3zzKbjUPRc2hOzGAdEf4/Dz+WJwBvEYL/lkkIsI3ihufq9hk9K4lVoK" crossorigin="anonymous">
<title>Multi Image Tutorial</title>
</head>
<body>
<div class="container py-4">
{% block content %}
{% endblock %}
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
blog.html
{% extends 'base.html' %}
{% block content %}
<div class="row row-cols-1 row-cols-md-2">
{% for post in posts %}
<div class="col mb-4">
<div class="card">
<div class="view overlay">
<img class="card-img-top" src="{{post.image.url}}"
alt="Card image cap" >
<a href="#">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<div class="card-body">
<h4 class="card-title">{{post.title}}</h4>
<p class="card-text">{{post.description}}</p>
Read More
</div>
</div>
<!---card-->
</div>
{% endfor %}
</div>
{% endblock %}
detail.html
{% extends 'base.html' %}
{% block content %}
<div id="carouselExampleIndicators" class="carousel slide" data-mdb-ride="carousel">
<ol class="carousel-indicators">
{% for p in photos %}
<li data-mdb-target="#carouselExampleIndicators" data-mdb-slide-to="{{forloop.counter0}}" class="{% if forloop.counter0 == 0 %} active {% endif %}"></li>
{% endfor %}
</ol>
<div class="carousel-inner" role="listbox">
{% for p in photos %}
<div class="carousel-item {% if forloop.counter0 == 0 %} active {% endif %}">
<img
src="https://mdbootstrap.com/img/new/slides/041.jpg"
class="d-block w-100"
alt="First slide"/>
</div>
{% endfor %}
</div>
<a
class="carousel-control-prev"
href="#carouselExampleIndicators"
role="button"
data-mdb-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</a>
<a
class="carousel-control-next"
href="#carouselExampleIndicators"
role="button"
data-mdb-slide="next" >
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</a>
</div>
{% endblock %}
urls.py
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from posts import views
urlpatterns = [
url(r'^youadmin/', admin.site.urls),
url(r'^', views.blog_view, name='blog'),
url(r'^<int:id>/', views.detail_view, name='detail'),
] + static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You are using the url function which expects you to use regex to capture arguments, to capture an integer your patterns should be like:
urlpatterns = [
url(r'^youadmin/', admin.site.urls),
url(r'^', views.blog_view, name='blog'),
url(r'^(?P<id>\d+)/', views.detail_view, name='detail'),
]
But i would recommend you to use the path function instead, which doesn't require regex:
from django.urls import path
urlpatterns = [
path('youadmin/', admin.site.urls),
path('', views.blog_view, name='blog'),
path('<int:id>/', views.detail_view, name='detail'),
]
You must include a trailing slash at the beginning of your urls like this:
urlpatterns = [
url(r'^/youadmin/', admin.site.urls),
url(r'^/', views.blog_view, name='blog'),
url(r'^/<int:id>/', views.detail_view, name='detail'),
]
It's also possible that an instance of Post with id=1 just doesn't exist.

Django Polls Project: Reverse for 'polls.index' not found

I'm trying to finish my Django Polls Project from the Django Documentation but I ran into the "Reverse for 'polls.index' not found. 'polls.index' is not a valid view function or pattern name." error.
The full error details can be seen here
The following are my files.
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous"
/>
<title>Pollster {% block title %}{% endblock %}</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 m-auto">
{% block content %}{% endblock %}
</div>
</div>
</div>
</body>
</html>
index.html
{% extends 'base.html' %}
{% block content %}
<h1 class="text-center mb-3">Poll Questions</h1>
{% if latest_question_list %}
{% for question in latest_question_list %}
<div class="card mb-3">
<div class="card-body">
<p class="lead">{{ question.question_text}}</p>
Vote Now
Results
</div>
</div>
{% endfor %}
{% else %}
<p>No polls available</p>
{% endif %}
{% endblock %}
mysite.urls
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
polls.urls
from django.urls import path
from . import views #from ALL import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
polls.views
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .models import Question, Choice
# Get questions and display them
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
# Show specific question and choices
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
# Get question and display results
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
# Vote for a question choice
def vote(request, question_id):
# print (request.POST['choice'])
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
detail.html
{% extends 'base.html' %}
{% block content %}
Back To Polls
<h1 class="text-center mb-3">{{ question.question_text }}</h1>
{% if error_message %}
<p class="alert alert-danger">
<strong>{{ error_message }}</strong>
</p>
{% endif %}
<form action="{% url 'polls:vote' question.id %}" method ="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<div class="form-check">
<input type="radio" name="choice" class="form-check-input" id="choice{{ forloop.counter }}" value = "{{ choice.id }}"/>
<label for="choice{{ forloop.counter }}">
{{ choice.choice_text }}
</label>
</div>
{% endfor %}
<input type="submit" value ="Vote" class ="btn btn-success btn-lg btn-block mt-4" />
</form>
{% endblock %}
I am new to Django and I would like to learn methods to find out where the errors could be originating from. I checked the code in reference with this finished project from the channel I'm watching but couldn't find the error I made.
Where could the error in my code be?
I researched and this stackoverflow question might be the same as mine but was not solved as well.
Here is my folder structure
I am also new to python for web development so any tips on how I could study this would be helpful. Thank you in advanced!

How to fix NoReverseMatch at / Reverse for 'post_detail' with keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried: ['post/<int:pk>/']

I have tried everything i found on the internet which was similar to my problem, but it did not help. Please help if you know the answer.
I get an ERROR while trying to set up my post_detail page of my blog.
The ERROR MESSAGE:
Reverse for 'post_detail' with keyword arguments '{u'pk': ''}' not found.
1 pattern(s) tried: ['post/<int:pk>/']
My post_list.html
{% extends "blog/base.html" %}
{% load static %}
<html>
<head>
<title>Code Reminder</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="{% static 'css/blog.css' %}">
<link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
</head>
<body>
<div class="page-header">
<h1>Coder Reminder</h1>
</div>
<div class="content container">
<div class="row">
<div class="col-md-4">
{% block content %}
{% for post in posts %}
<div class="post">
<div class="date">
{{ post.published_date }}
</div>
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endfor %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
My post_detail.html
{% extends "blog/base.html" %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h2>{{ post.title }}</h2>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endblock %}
My base.html
{% load static %}
<html>
<head>
<title>Code Reminder</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="{% static 'css/blog.css' %}">
<link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
</head>
<body>
<div class="page-header">
<h1>Code Reminder</h1>
</div>
<div class="content container">
<div class="row">
<div class="col-md-8">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
my views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Create your views here.
from django.shortcuts import render
from django.utils import timezone
from .models import Post
from django.shortcuts import render, get_object_or_404
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, '/home/ud/PycharmProjects/blog/blog/blog/templates/blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, '/home/ud/PycharmProjects/blog/blog/blog/templates/blog/post_detail.html', {'post': post})
My urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url('', views.post_list, name='post_list'),
url('post/<int:pk>/', views.post_detail, name='post_detail'),
]
And finally my myblog/urls.py
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('blog.urls')),
]
Please help me if you know the answer. I really tried everything but i cant find out my mistake.
Regards
The error message says
Reverse for 'post_detail' with keyword arguments '{u'pk': ''}' not found.
Which shows that the pk is evaluating to the empty string ''.
Your URL tag is
{% url 'post_detail' pk=post.blog.pk %}
That means you are trying to pass the post's blog's pk. But you almost certainly want the post's pk instead:
{% url 'post_detail' pk=post.pk %}
Secondly, you are using the old url() with the path() syntax (new in Django 2.0). Your urls should be:
from django.urls import path
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
The problem might be due to the older version of Python or Django.
Try changing your My urls.py file as follow:
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
]
Here it will help to parse the address properly. If it still doesn't work the try to replace following in My post_list.html file
Old:
{% url 'post_detail' pk=post.blog.pk %}
New:
{% url 'post_detail' pk=post.pk %}
Hope this will help!

Django Form is not visible in Inherited template

I am using template inheritance in my django project. I used form in my base html page and submit button, When i inherit base template to another template form get disappeared but submit button is still there. I have below templates.
base.html
<head>
{% load static from staticfiles %}
<link rel="stylesheet" href="{% static "bootstrap.css" %}">
</script>
</head>
<body>
{% block option %}
<div class="row">
<div class="col-lg-3">
<form method = "post" action="">
{% csrf_token %}
{{form}}
<input type="submit" value="Submit" />
</form>
</div>
</div>
{% endblock %}
<div class="row">
{% block content %}{% endblock %}
</div>
</body>
chart.html
{% extends 'base.html' %}
{% block content %}
<head>
{% load static from staticfiles %}
<link rel="stylesheet" href="{% static "bootstrap.css" %}">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
</script>
</head>
<div id="container" align="center">
{{ column_chart.as_html }}
{% endblock %}
How can i make form visible there in chart html??
EDIT: Added Views
views.py
def select_chart_form(request):
form = SelectChart(request.POST)
if form.is_valid():
if (str(form.cleaned_data['status']) == '1'):
#print "Hello Naresh reverse('chart1')"
return HttpResponseRedirect('/chart1/')
if (str(form.cleaned_data['status']) == '2'):
return HttpResponseRedirect('/chart2/')
context = {
'form' : form
}
return render(request, 'base.html', context)
def video_by_user(request):
analysis = VideoData.objects.annotate(watches_count = Count('user')).order_by('-watches_count')[:10]
data_source = ModelDataSource(analysis,fields=['video_name', 'watches_count'])
column_chart = gchart.ColumnChart(data_source,options={'title': "Top 10 Videos watched by No. Of Users"})
context = {
"data_source": data_source,
"column_chart": column_chart,
}
return render_to_response('chart.html', context)
I am calling video_by_user method..after click on submit button.
The select_chart_form and video_by_user views are completely separate. The first one renders just base.html, and supplies the form variable when it does so. The second one renders chart.html, which inherits from base.html, but it only supplies the variables needed for chart.html itself: it doesn't provide the form needed for base.html. You will need to supply that in video_by_user.

Adding css i js to python templates

I have a problem with including css and js files. My index page works fine, but when I try to put the same code to the detail page it doesn't work, not even html wich I wrote on detail.html, just the include files from master.html work. What can be the problem?
master.html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="static/font.min.css" rel="stylesheet">
<link href="static/bootstrap.min.css" rel="stylesheet">
<link href="static/font-awesome.min.css "rel="stylesheet">
<link href="static/main.css" rel="stylesheet">
</head>
<body data-spy="scroll" data-target="#navbar" data-offset="0">
{% include "header.html" %}
{% include "carausel.html" %}
{% block h1 %}{% endblock %}
{% include "footer.html" %}
<script src="static/jquery.js"></script>
<script src="static/bootstrap.min.js"></script>
<script src="static/jquery.isotope.min.js"></script>
<script src="static/jquery.prettyPhoto.js"></script>
<script src="static/main.js"></script>
</body>
detail.html
{% extends "master.html" %}
{% block h1 %}
<div class="box first">
<div class="row">
<div class="container">
{% for question in latest_question_list %}
<div class="col-xs-12 col-sm-4 col-md-3">
<div class="center">
<h4>{{ question.naslov }} </h4>
<p>{{ question.opis }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
{% block title %} Detail {% endblock %}
views.py
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.all()
context = {'latest_question_list': latest_question_list}
return render(request, 'papers/index.html', context)
def detail(request, slug):
question = Question.objects.get(slug=slug)
return render(request, 'papers/detail.html', {'question': question})
urls.py
from django.conf.urls import include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
urlpatterns = [
url(r'^$', 'papers.views.index', name='index'),
url(r'^admin/', include(admin.site.urls)),
url(r'^(?P<slug>[\w_-]+)/$', 'papers.views.detail', name='detail'),
]
urlpatterns += staticfiles_urlpatterns()
Use absolute paths for all your static links.
<link href="/static/....
<script src="/static/...

Categories

Resources