Getting an empty query set Django - django

I'm trying to develop a search functionality but only getting a empty query set every single time .
class SearchView(TemplateView):
template_name = "search.html"
def get_context(self, **kwargs):
context = super().get_context(**kwargs)
kw = self.request.GET.get("search")
results = Thread.objects.filter(Q(heading__icontains=kw) | Q(thread_content__icontains=kw))
print(results)
context["results"] = results
return context
Template
{% extends 'base.html' %}
{% block title %}Search{% endblock %}
{% block content %}
<div class = "container">
<div class = "row">
<div class = "col-md-12">
<h3>Search results for <span class="text-info">"{{ request.GET.search }}"</span></h3>
<h3>{{results}}</h3>
<hr>
{% for item in results %}
<div class="col-md-4">
<img src = "{{item.image.url}}" class="img-fluid" alt = "">
</div>
<div class="col-md-8">
<h4>{{item.heading}}</h4>
<p>{{item.thread_content}}</p>
</div>
{%endfor%}
</div>
</div>
</div>
{% endblock %}
request.GET.search is returning correctly , but the rest is not getting displayed

This was a real strange issue. The Browser cache took a long time to refresh with my updated code. Once I cleared the Browser Cache and Settings, it started working again.

Related

Have issues getting data to display on my web application

I am trying to get the "About us" information from my database to my web application but its not displaying, what could be wrong...
here is the code from the database
class About(models.Model):
about_us = models.TextField()
achieve = models.TextField(blank=True)
image_abt = models.ImageField(upload_to="admin_pics", null=True)
class Meta:
verbose_name_plural = "About Us"
def __str__(self):
return self.about_us
and here is the Html code `
{% extends 'jtalks/base.html' %}
{% load static %}
{%block content%}
<section id="about-home">
<h2>About Us</h2>
</section>
<section id="about-container">
{% for about in abouts %}
<div class="about-img">
<img src="{{ about.image_abt.url }}" alt="">
</div>
<div class="about-text">
<h2>Welcome to TechEduca, Enhance your skills with best Online Courses</h2>
<p>{ about.about_us}</p>
<div class="about-fe">
<img src="images/fe1.png" alt="">
<div class="fe-text">
<h5>400+ Courses</h5>
<p>You can start and finish one of these popular courses in under our site</p>
</div>
</div>
<div class="about-fe">
<img src="images/fe2.png" alt="">
<div class="fe-text">
<h5>Lifetime Access</h5>
<p>You can start and finish one of these popular courses in under our site</p>
</div>
</div>
</div>
{% endfor %}
</section>
{% endblock %}
Nothing is displaying in the frontend of the website.
Thanks for sharing the view. You forgot to pass data to your template. To do that you have to create the queryset and pass that into a dictionary like below. Add the context variable to your render method so you can access the data in the template.
def about(request):
about = About.objects.all()
context = {
'abouts': about,
}
return render(request, 'jtalks/about.html', context)
also, in your html code i see { about.about_us}, but you have to use double curly brackets: {{ about.about_us }}

How to make a div appear only once in a loop?

I've created a model Team in models.py in Django for which I've created in views.py the following code:
def team(request):
obj = Team.objects.all().order_by('?')
context = {'team': obj}
return render(request, 'website/team.html', context)
In HTML I've created a team loop which is displaying all the team members available.
{% for team in team %}
<div class="member animated delay1" data-effect="fadeInUp">
<div class="team-image">
<div class="teamDescription">
<p>{{ team.description }}</p>
</div>
<img src="{{ team.picture.url }}">
</div>
<div class="blueLine"></div>
<div class="team-name-function animated delay1" data-effect="fadeInUp">
<h5>{{ team.name }} {{ team.surname }}</h5>
<p>{{ team.title }}</p>
</div>
</div>
{% endfor %}
In this loop, I need to make available one div with the numbers of team members, which has to appear only once and randomly as team members. Currently I have <div class="number">{{ team.count }}</div> outside the loop.
How do I integrate the members counting in the loop and make it appear only once?
Thank you in advance for any solution!
In the view use teams instead of team: context = {'teams': obj}
create a random number between 1 and teams length in view
import random
....
random_number = random.randint(a,len(teams)) # insert it after teams
...
context = {
'team': obj,
'random' : random_number,
}
then in the template use {% for team in teams %}
and if you want to show teams length just one time it's possible to use
{% if forloop.counter==random %}
<div class="number">{{ teams.count }}</div>
{% endif %}

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

Help me please!
Sorry about my english , i'm weak in english!
I am trying to visit this page 192.168.56.102 / project / BP / 4, it shows me this msg error!
the same configurations of urls and views with other page it works fine.
Reverse for '' not found. '' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://192.168.56.102/project/BP/4
Django Version: 2.1.7
Exception Type: NoReverseMatch
Exception Value:
Reverse for '' not found. '' is not a valid view function or pattern name.
urls.py :
urlpatterns = [
#Project :
path('', views.projects , name = 'project'),
path('BP/<int:id_project>', views.tb_project , name='tb_project'),
path('add/', views.add_project , name = 'add_project'),
path('delete/p/<int:id_project>',views.delete_project , name='delete_project'),
path('edit/<int:id_project>' , views.edit_project , name = 'edit_project'),
#Zone Action :
path('zone/<int:id_project>/' , views.list_zones , name ='list_zone'),
path('zone/add/<int:id_project>/' , views.add_ZoneAction , name = 'add_zone'),
path('delete/z/<int:id_project>/<int:id_zone>',views.delete_zone , name='delete_zone'),
path('zone/edit/<int:id_zone>' , views.edit_ZoneAction , name = 'edit_zone'),
]
views.py :
def tb_project(request,id_project):
template ="project/bord_project.html"
context = {}
prj = get_object_or_404(project ,id = id_project)
context["prj"] = prj
return render(request, template ,context)
page.html
<a href="{% url 'tb_project' element.id %}">
<!-- element.id = 4 -->
the link is displayed correctly in the page : 192.168.56.102/project/BP/4 but when I click to go to bord_project.html I see an error msg!
Page.html :
list_tuple is context variable
{% extends "base.html" %}
{% load static %}
{% block contenu %}
<div class="container">
{% for elements in list_tuple %}
<div class="row" style="margin-top : 10px;">
{% for element in elements %}
<div class = "col-4">
<div class="card text-center">
<div class="card-header">
Projet
</div>
<div class="card-body">
<h5 class="card-title">
{{ element.intitule }}
</h5>
<p class="card-text">
{{ element.description|truncatewords:7 }}
</p>
<a href="{% url 'tb_project' element.id %}" class="btn btn-info">
{# link #}
Plus ยป
</a>
</div>
<div class="card-footer text-muted">
{{ element.date }}
</div>
</div>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
for the moment bord_project.html is blank
{% extends "base.html" %}
{% load static %}
{% block contenu %}
{# blank for the moment #}
{% endblock %}
I do not believe the issue is in any code that you have pasted. You should run a $ grep -r -E "reverse|url" . or similar search command to find any url resolutions that you might be missing.
Somewhere you have a reverse[_lazy] function call or url templatetag that is performing a bad lookup.
Make sure that any uses of the url templatetag are using quotes around the view name.

Django iteration (for ... in ...) how to put it in different divs?

I have few instances of model.
my model:
class Record(models.Model):
name = models.ForeignKey(Car)
image = models.ImageField(upload_to='images/')
created = models.DateTimeField(
default=timezone.now)
view:
def allrecords(request):
records = Record.objects.all().order_by('created')
return render(request, 'mycar/allrecords.html', {'records' : records})
I want show it on my website. In my template i have:
{% for record in records %}
<img src={{ record.image.url}}/>
<div>
{{record.name}}
</div>
{% endfor %}
Now i get list of my records, but i would like put the newest record to first div, next to second etc. How can i do that?
I show simple screen how i would like have that (if someone will create new record, it will go to first div and other records will change place. Is any possibility to do something like that?
edit:
<div>
{% for record in records %}
{% if forloop.counter == 1 %}
<img src={{ record.image.url}}/>
<div>
{{record.name}}
</div>
{% endif %}
{% endfor %}
</div>
<div>
{% for record in records %}
{% if forloop.counter == 2 %}
<img src={{ record.image.url}}/>
<div>
{{record.name}}
</div>
{% endif %}
{% endfor %}
</div>
.
.
# till your 5th image
You can use forloop.counter to get the iteration number and check what is the iteration the loop and handle data accordingly.
In addition you can use CSS to make the layout work as you want.
Here is the information for Django template counter
Edit :
{% for record in records %}
<div>
{% if forloop.counter == 1 %}
# Here you can get your first images
<img src={{ record.image.url}}/>
<div>
{{record.name}}
</div>
{% endif %}
</div>
<div>
{% if forloop.counter == 2 %}
# Here you can get your first images
<img src={{ record.image.url}}/>
<div>
{{record.name}}
</div>
{% endif %}
</div>
.
.
# till your 5th image
{% endfor %}
There are two ways to do this. If you want to set this option for a single view then:
def all_records(request):
records = Record.objects.all().order_by('-created')
return render(request, 'mycar/allrecords.html', {'records' : records})
You're almost correct but order_by('created') leads to asceding order while order_by('-created') leads to descending order which is what you require.
Alternatively, if you want to have this setting to apply to all views then set class Meta in your models.py which will ensure that wherever you use Record.objects.all() it returns Records in descending order of created field:
class Record(models.Model):
name = models.ForeignKey(Car)
image = models.ImageField(upload_to='images/')
created = models.DateTimeField(
default=timezone.now)
class Meta:
ordering = ('-created')
It's Django design pattern to make all logical decisions in models and views and only just plugin formatted data in templates. You shouldn't add any complex logic in templates.
I'm assuming the question means that the model might have more than 5 records. If so, a more generic solution would be
<div class='row'>
<div class='firstimage'>
<img src={{ records[0].image.url}}/>
{{record.name}}
</div>
{% for record in records %}
{% if forloop.counter > 1 %}
<div class='subsequentimage'>
<img src={{ record.image.url}}/>
{{record.name}}
</div>
{% endif %}
{% cycle "" "</div><div class='row'>" "" %}
{% endfor %}
</div>
Note the use of the 'cycle' tag to begin a new row div every third cell div.
I don't know what your CSS classes are to distinguish between rows and cells so I used 'row', 'firstimage' (which might be defined to take up twice as much width) and 'subsequentimage' as example classes.
I recommend you to use the context variables:
def all_records(request):
records = Record.objects.all().order_by('-created')
newest = records[:5]
oldest = records[5:]
return render(request, 'mycar/allrecords.html', {'newst' : newest,
'oldest': oldest })
In your template :
{% for new in newst %}
<div>what you want with news</div>
{% endfor %}
{% for old in oldest %}
<div>what you want with olds</div>
{% endfor %}

Object Not Iterable

I am having an odd problem... This code was working fine until I worked on some of the other views, and now, it isn't working.
Here is my view:
def showTickets(request, project_slug):
project = Project.objects.get(slug=project_slug)
tickets = Ticket.objects.get(project=project)
payload = { 'project':project, 'tickets':tickets}
return render(request, 'project/tickets.html', payload)
Template:
{% extends 'project/base.html' %}
{% block title %}Tickets: {{project.name}}{% endblock %}
{% block main %}
<div id="project-nav">
<span>Tickets</span>
<span>Docs</span>
<span>Browser</span>
</div>
<div id="action-nav">
{% block actions %}
<span>Create Ticket</span>
<span>Recent Activity</span>
<span>My Tickets</span>
{% endblock %}
</div>
{% for ticket in tickets %}
<div class="ticket">
<div class="ticket-header">
<div class="ticket-title">
{{ticket.subject}}
</div>
<div id="ticket-number">
#{{ticket.pk}}
</div>
<div id="ticket-state">
{{ticket.get_state_display}}
</div>
<div id="ticket-info">
Reported by {{ticket.created_by}} | created: {{ticket.created_on }} | modified: {{ticket.modified_on}}
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
Error:
Template error:
In template c:........\project\tickets.html, error at line 19
Caught TypeError while rendering: 'Ticket' object is not iterable
This was working fine until I worked on some other views...not sure why it isn't working now? If any one can help I'd appreciate it!
project = Project.objects.get(slug=project_slug)
tickets = Ticket.objects.get(project=project)
These two lines are the cause of your troubles. They aren't returning an iterable, such as a list, but an object, which isn't iterable at all. Instead of a get, use a filter instead, which will return a list.
The get() method returns a single object. Perhaps you meant to use the filter() method instead?