Django search bar not getting to the right page - django

My page has two ways to search services - one is a search bar and the other is clickable categories. The clickable category go to a page that has a category primary key attached to the view and the search bar results do not have a category pk attached. Thus, I created two separate views for this reason. The problem is that both views go to the same page the index.html. I want the search bar to go to the index_search.html. I think I set-up everything correctly, but it still does not work.
Two views: search view, clickable items view:
#search form view
def service_finder(request):
model = Service
if ('s' in request.GET) and request.GET['s'].strip():
query_string = request.GET['s']
#get query is just searching for search terms in those fields of the query set
entry_query = get_query(query_string,['description', 'tags', 'category'])
table = Service.objects.filter(entry_query)[:60]
return render(request, 'index_search.html', {'table': table})
#clickable items view
def servicesListView(request, category):
model = Service
table = Service.objects.filter(category=category)[:60]
return render(request, 'index.html', {'table': table})
Here is the html template with both the search bar and clickable items:
{% block content %}
<main class="category">
{% include "search_form.html" %}
<section class="category-list">
<div class="container">
<div class="row">
{% for service in service_cat %}
<div class="col-sm-12 col-lg-6">
<a
href="{% url 'services_list' service.category %}"
{{ service.category }}
</a>
</div>
{% endfor %}
</div>
</div>
</section>
</main>
{% endblock %}
Here is the search bar file or search_form.html:
<div class="search-bar">
<div class="container">
<form method="get" action="{% url 'service_finder' %}">
{% csrf_token %}
<div class="input-group">
<input name='s' value="{{request.GET.s}}" type="text" class="form-control" placeholder="Search services" aria-label="Search" aria-describedby="search">
<div class="input-group-append">
<button class="btn btn-secondary" type="submit" id="button-addon2">Go</button>
</div>
</div>
</form>
</div>
</div>
Here is the urls for the two pages:
path('services/<category>/', views.servicesListView, name='services_list'),
path('services/find/', views.service_finder, name='service_finder'),
SOLVED:
Fixed this by switching the order of the urls.

It's because the path /services/find/ matches the previous pattern /services/<category>/. Just explaining the reason why the fix worked!

Related

How can i render objects in html through django templating via primary key?

i have a problem in searching articles on my home page. the problem is that when i enter a query in a search bar , the error "Reverse for 'blog_detail/' not found. 'blog_detail/' is not a valid view function or pattern name." appears.
code
homepage from where i search a query
<form method="get" action={% url 'search' %} class="">
<!-- <form method="get" action="{% url 'search' %} class="">-->
<input type="text" name="search" class="form-control bg-dark text-white" placeholder="Search Articles" aria-label="Recipient's username" aria-describedby="basic-addon2">
<div class="input-group-append bg-dark">
<button class="btn btn-outline-primary bg-danger text-white" type="submit" >Search </button>
</div>
</form>
search.html
The action of the form sends query to this page
<div class="row">
{% for item in post %}
<div class="card my-3 text-white bg-dark mb-3" style="width: 18rem;">
<img src="/media/{{item.thumbnail}}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{item.title}}</h5>
<p class="card-text">{{item.intro}}</p>
read more...
</div>
</div>
{% if forloop.counter|divisibleby:5 %}
</div>
{% endif %}
{% endfor %}
</div>
this (href="{% url 'blog_detail/' id=item.post_id %}") is giving an error saying (NoReverseMatch at /search/)
in the urls.py the route for blog_detail is : path("blog_detail/<int:id>", views.blog_detail, name = "blog"),
and for search route is : path("search/", views.search, name="search"),
in the models the primary key is set as post_id : post_id = models.AutoField(primary_key=True)
i hope this information is enough....!
The first parameter of the {% url … %} template tag [Django-doc] is the name of the path. So you should write this as:
href="{% url 'blog' id=item.post_id %}"
since in your urlpatterns, you wrote:
urlpatterns = [
# …
path("blog_detail/<int:id>", views.blog_detail, name="blog"),
# …
]

Django display content based on dropdown select

I am new in Django.
I want to display content based on dropdown selection.
In this example i want to show all the workshops data from the location selected in the dropdown.
Is it possible to achieve that without reloading the page? or if it must reload the page, is it possible to stay on current view after reloading the page?
Thank you.
I have tried to use post method and use onChange attribute on my forms.
It successfully reload the page but the workshops content is not shown, the dropdown selection go back to default '--- Choose your location ---' and the page go back to the top.
Below is the code of the forms
class LocationForm(forms.Form):
location = forms.ModelChoiceField(label='', queryset=Location.objects.all(), empty_label="--- Choose your location ---",
widget=forms.Select(
attrs={'id': 'ddlLocation', 'name':'ddlLocation', 'class':'selectpicker', 'data-live-search':'true', 'data-size':'5', 'onChange':'frLocation.submit();' }
)
)
Below is the code of the class
class HomeView2(ListView):
template_name = 'myapp/index.html'
def get(self, request):
form_location = LocationForm()
location_id = request.GET.get('location_id')
workshops = Workshop.objects.filter(location_id=location_id).order_by('workshop_name')
args = {'form_location':form_location, 'workshops':workshops}
return render(request, self.template_name, args)
def post(self,request):
form_location = LocationForm()
location_id = request.GET.get('location_id')
workshops = Workshop.objects.filter(location_id=location_id).order_by('workshop_name')
args = {'form_location':form_location, 'workshops':workshops}
return render(request, self.template_name, args)
and in index.html
<section class="page-section" id="services">
<div class="container">
<h2 class="text-center mt-0">At Your Service</h2>
<hr class="divider my-4">
<div class="row justify-content-center">
<div class="col-lg-3 col-md-6 text-center">
<div class="mt-5">
<i class="fas fa-4x fa-wrench text-primary mb-4"></i>
<h3 class="h4 mb-2">Select location</h3>
<form id="frLocation" name="frLocation" method="POST">
{% csrf_token %}
{{form_location}}
</form>
</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-lg-3 col-md-6 text-center">
<div class="mt-5">
<form id="frWorkshop">
{% for workshop in workshops %}
<p>Workshop: {{workshop.workshop_name}}</p>
{% endfor %}
</form>
</div>
</div>
</div>
</div>
</section>

Django 1.11: pass id to url to generate detail view

I've a list of "nanas" (babysitters) that I render correctly. Now I need that when someone clicks on one of them , a detail page (for only the clicked nana opens).
I think my problem is on my template for all the Nanas, in the href:
<a href="{% url 'app-administrador:nana' nana.id %}">
Or in the Urls.
All Nanas page:
This is listing nanas View:
class NanasView(View):
def get(self, request):
nanas = Nana.objects.all()
context = {'nanas': nanas}
return render(request, 'app_administrador/nanas-registradas.html', context)
It's URL:
url(r'^referencias_de_nanas', views.NanasReferenciasView.as_view(), name='referencias_de_nanas'),
All Nanas templates:
{% extends 'app_administrador/templates/base.html' %}
{% load staticfiles %}
{% block content %}
<!-- Member Entries -->
{% for nana in nanas %}
<!-- Single Member -->
<div class="member-entry">
<a href="extra-timeline.html" class="member-img">
<i class="entypo-forward"></i>
</a>
<div class="member-details">
<a href="{% url 'app-administrador:nana' nana.id %}">
<h4>
<p href="extra-timeline.html">{{ nana.nombre }} {{ nana.apellido_paterno }} {{ nana.apellido_materno }}</p>
{% if nana.foto %}
<img src="{{ nana.foto.url }}" class="img-rounded" width="160px"/>
{% endif %}
</h4>
<!-- Details with Icons -->
<div class="row info-list">
<div class="col-sm-4">
<i class="entypo-briefcase"></i>
<a href={{ nana.antecedentes_policiales }}>Antecedentes policiales</a>
</div>
<div class="col-sm-4">
<i class="entypo-twitter"></i>
#johnnie
</div>
<div class="col-sm-4">
<i class="entypo-facebook"></i>
fb.me/johnnie
</div>
<div class="clear"></div>
<div class="col-sm-4">
<i class="entypo-location"></i>
{{ nana.direccion }}
</div>
<div class="col-sm-4">
<i class="entypo-mail"></i>
{{ nana.correo }}
</div>
<div class="col-sm-4">
<i class="entypo-linkedin"></i>
johnkennedy
</div>
</div>
</a>
</div>
</div>
{% endfor %}
{% endblock %}
Nana's detail page:
My try on showing the detail page for clicked nana:
class NanasValidarReferenciasView(View):
def get(self, request, nana_id):
# nana_id_is = nana_id
nana = Nana.objects.get(id=nana_id)
context = {'nana': nana}
return render(request, 'app_administrador/validar-referencias-nana.html', context)
It's URL:
url(r'^nana', views.NanasValidarReferenciasView.as_view(), name='nana'),
You see your href looks like this: <a href="{% url 'app-administrador:nana' nana.id %}"> which is totally fine. This means that the url link adds the two string together into one address. I don't know exactly how your urls are set up so it could look something like this:
root_url/2
Where root_url is whatever you have and 2 is the nana.id. To pass that to the url-view, it needs to accept any integer variable. Something like this:
urls.py
url(r'^nana/(?P<nana_id>\d+)/$', views.nanas_specific, name='nana'),
The P stands for Parameter, and it uses Regex logic if you want to look that up.
Then in your views, you can have a function ready to accept the parameter:
views.py
def nanas_specific(request, nana_id):
Where nana_id contains the result from the urls parsing.
I mostly work with function based views, but I'm assuming the same logic applies to classbased views. The id is not part of the URL and hence is not passed on. Change the url to
url(r'^nana/(?P<nana_id>\d+)/$', views.NanasValidarReferenciasView.as_view(), name='nana'),

Django search bar problems

I'm trying to implement a search bar to my website, it's not working and I can't seem to figure out why. The search form looks like this:
<form class="navbar-form navbar-left" role="search" method="GET" action="{% url 'search' %}">
<div class="form-group">
<input type="text" class="form-control" name="q" value="{{request.GET.q}}">
</div>
<button type="submit" class="btn">Search</button>
</form>
url.py:
url(r'^search/$', views.SearchView, name='search'),
views.py:
def SearchView(request):
products = Photos.objects.all()
query = request.GET.get("q")
if query:
products = products.filter( Q(category__contains=query) ).distinct()
return render(request, 'urcle/search.html', {'products': products})
else:
return render(request, 'urcle/search.html', {'products': products})
search.html:
{% extends 'urcle/base.html'%}
{%block content%}
{% if products %}
<div id="inner" >
{% for item in products %}
<div id = 'content' align="center" ></div>
<div class="col-sm-4 col-lg-2" style="width:30%" >
<div class="thumbnail" align="left" >
<a href="{{item.name}}">
<img src="http://ec2-54-194-123-114.eu-west-1.compute.amazonaws.com/images/{{ item.name }}.jpg" class="img-responsive">
</a>
<div class="caption" >
{{item.title}} </li>
<br/>
</div>
</div>
</div>
{% cycle '' '' '' '' '' '<div class="clearfix visible-lg"> </div>' %}
{% endfor %}
</div>
{% else %}
<h1>nothing to see here!!!</h1>
{% endif %}
{%endblock%}
What's really bugging me is that all that gets displayed is the part that gets extended from base.html not even the tag on the else statement gets displayed, anyone know whats up?
The problem was a conflicting URL, which was taking me to the wrong view function

Django Bootstrap form field won't resize

I am using bootstrap to display my django forms but am having trouble getting them to resize. One of the forms is a text input area and I want it to span most of my panel width. I've tried multiple things but haven't been able to resize it/make the input area bigger.
The html:
<div class="container-fluid">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="text-center">
Raw sQL Query
</h4>
</div>
<form action="/InterfaceApp/table_search/" method="post" class="form">
{% csrf_token %}
<div class="panel-body text-center">
{% bootstrap_form rawsQL %}
</br>
<div class="container-fluid">
<button type="submit" class="btn btn-primary center-block" value="Submit" name="rawsQL">
{% bootstrap_icon "fire" %} Submit
</button>
</div>
</div>
</form>
</div>
The form:
class TextFieldForm(forms.Form):
def __init__(self,*args,**kwargs):
section_label = kwargs.pop('section_label')
initial_value = kwargs.pop('initial_value')
required_val = kwargs.pop('required')
super(TextFieldForm,self).__init__(*args,**kwargs)
self.fields['text'].label=mark_safe(section_label)
self.fields['text'].initial=initial_value
self.fields['text'].required=required_val
text = forms.CharField()
Right now it looks like this:
Can anyone help me with making the input area wider??
Have a look at grid system and form control sizing.
So it turns out that when you pass in forms to django templates like {% bootstrap_form formname %} you have to go into where you defined the form to edit how it looks. I fixed my resizing issue by doing:
Form:
class TextFieldForm(forms.Form):
def __init__(self,*args,**kwargs):
section_label = kwargs.pop('section_label')
initial_value = kwargs.pop('initial_value')
required_val = kwargs.pop('required')
super(TextFieldForm,self).__init__(*args,**kwargs)
self.fields['text'].label=mark_safe(section_label)
self.fields['text'].initial=initial_value
self.fields['text'].required=required_val
text = forms.CharField(widget=forms.TextInput(attrs={'class':"form-control text-center",'placeholder':".col-md-8"}))
html:
<div class="col-md-8 centering">
{% bootstrap_form rawsQL %}
</div>