Search function returning nothing -Django - django

def Search(request):
if request.method == 'GET' and request.GET['x']:
parameter = request.GET['x']
results = Category.objects.filter(advert__Seller_Name__icontains = parameter)
return render(request, 'campusbuy/search.html', {'results': results})
else:
return render(request, 'campusbuy/search.html')
Above is my search function. When I try to search for an object in my template, it returns nothing. However, when I deliberately search for a Seller_name that's not in the db it returns the {% else %} value. Below is the template:
% extends 'campusbuy/base.html' %}
{% block content %}
{% if results %}
{% for ads in results.advert_set.all %}
<p>{{ads.Seller_Name }}</p>
<p>{{ads.Location}}</p>
<p>{{ads.Description}}</p>
<p>{{ads.Asking_Price}}</p>
{% endfor %}
{% else %}
<p>No Ad matched your search criteria.</p>
{% endif %}
{% endblock %}
Here's the models.py:
class Category(models.Model):
Name = models.CharField(max_length=20, null=True, blank=True)
Details = models.CharField(max_length=100, default="Default")
Category_Logo = models.ImageField(max_length=100, upload_to='uploads')
def __str__(self):
return self.Name
class Advert(models.Model):
HALL3 = 'HALL3'
HALL4 = 'HALL4'
HALL2 = 'HALL2'
MAIN_GATE = 'MAINGATE'
HALL1 = 'HALL1'
Location_Choices = (
(HALL3, 'Hall3'),
(HALL4, 'Hall4'),
(HALL2, 'Hall2'),
(MAIN_GATE, 'Main_gate'),
(HALL1, 'Hall1')
)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
Seller_Name = models.CharField(max_length=50, blank=False, null=False)
Phone_Number = models.CharField(max_length=11, blank=False, null=False,
help_text='<p style="color: red; font: italic 12px tahoma;">**Please input a working Phone Number that you can be contacted with on the fly</p>')
image = models.ImageField(max_length=100, upload_to='uploads')
Item = models.CharField(max_length=20, blank=False, null=False)
Location = models.CharField(max_length=10, choices=Location_Choices, default=HALL3, blank=False)
Description = models.TextField(max_length=250, blank=False, null=False)
Asking_Price = models.CharField(max_length=20, blank=False, null=False)
published_date = models.DateTimeField(blank=False, default=timezone.now)
Thank you in advance!

I still haven't understood why you've tried to include Category in the query, since you are not using it at all either in the query itself or in the template. Just query and use Adverts directly:
results = Advert.objects.filter(Seller_Name__icontains=parameter)
and iterate over it also directly:
{% for ads in results %}
<p>{{ads.Seller_Name }}</p>
<p>{{ads.Location}}</p>
<p>{{ads.Description}}</p>
<p>{{ads.Asking_Price}}</p>
{% endfor %}
Also note, you don't need the if block, because the for template tag has an [empty`](https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#for-empty) clause that is displayed if the loop was empty:
{% for ads in results %}
<p>{{ads.Seller_Name }}</p>
<p>{{ads.Location}}</p>
<p>{{ads.Description}}</p>
<p>{{ads.Asking_Price}}</p>
{% empty %}
<p>No Ad matched your search criteria.</p>
{% endfor %}

Related

How to display Data of foreign key in Django html page?

I want to display a Company header and the products below its related company. I am new to django i do not understand this fully.
My models.py
class Company(models.Model):
name = models.CharField(max_length=250)
def __str__(self):
return str(self.name)
class Products(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="display")
engine = models.CharField(max_length=250, blank=True)
cyl = models.CharField(max_length=250, blank=True)
bore = models.CharField(max_length=250, blank=True)
def __str__(self):
return str(self.engine) + " (ref:" + str(self.ref) + ")"
My views.py:
def Companies(request):
context = {
'categories': Company.objects.all()
}
return render(request, 'product_list.html', context)
My html:
{% for category in categories %}
<h2>{{ category.name }}</h2>
{% for item in category.item_set.all %}
{{ item_engine }}
{% endfor %}
{% endfor %}
only make changes to your HTML file as below and make sure the class name is Product if you are using product_set.all:
{% for category in categories %}
<h2>{{ category.name }}</h2>
{% for item in category.product_set.all %}
{{ item.engine }}
{% endfor %}
{% endfor %}
If still not working then try to remove : + " (ref:" + str(self.ref) + ")"
and also, I think by mistake you have displayed your models.py wrongly. The str functions should be inside the classes like below:
class Company(models.Model):
name = models.CharField(max_length=250)
def __str__(self):
return str(self.name)
class Product(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE,
related_name="display")
engine = models.CharField(max_length=250, blank=True)
cyl = models.CharField(max_length=250, blank=True)
bore = models.CharField(max_length=250, blank=True)
def __str__(self):
return str(self.engine)

DJANGO initial values in form not shown in template (some do some don't)

I have these Models, Tipos, Prioridad and Estado, related to Tarea
as defined below:
class Tipos(models.Model):
tipo = models.CharField(max_length=16,
verbose_name='tipo')
abrv = models.CharField(max_length=4,
null=True,
blank=True,
default='')
class Meta:
verbose_name = "Tipo"
verbose_name_plural = "Tipos"
def __str__(self):
return self.tipo
class Prioridad(models.Model):
prioridad = models.CharField(max_length=16,
verbose_name='prioridad')
abrv = models.CharField(max_length=4,
null=True,
blank=True,
default='')
orden = models.IntegerField(u'orden', blank=False)
class Meta:
verbose_name = "Prioridad"
verbose_name_plural = "Prioridades"
def __str__(self):
return self.prioridad
class Estado(models.Model):
estado = models.CharField(max_length=16,
verbose_name='estado')
abrv = models.CharField(max_length=4,
null=True,
blank=True,
default='')
class Meta:
verbose_name = "Estado"
verbose_name_plural = "Estados"
def __str__(self):
return self.estado
class Tarea(models.Model):
numtar = models.AutoField(primary_key=True)
cliente = models.ForeignKey(User,
related_name='user_cliente',
null=True,
on_delete=models.DO_NOTHING)
apoyo = models.ForeignKey(User,
related_name='user_apoyo',
null=True,
on_delete=models.DO_NOTHING)
asignado = models.ForeignKey(User,
related_name='user_asignado',
null=True,
on_delete=models.DO_NOTHING)
descorta = models.CharField(max_length=140)
deslarga = models.TextField(max_length=8195)
estado = models.ForeignKey(Estado,
null=True,
on_delete=models.SET_NULL)
tipo = models.ForeignKey(Tipos,
null=True,
on_delete=models.SET_NULL)
prioridad = models.ForeignKey(Prioridad,
null=True,
on_delete=models.SET_NULL)
creacion = models.DateTimeField(auto_now_add=True)
revision = models.DateTimeField(auto_now=True, blank=True)
cierre = models.DateTimeField(null=True, blank=True)
class Meta:
verbose_name = "Tarea"
verbose_name_plural = "Tareas"
def __str__(self):
return '%s' % (str(self.numtar))
and I call the following view:
#login_required(login_url='/login')
def newincid_view(request):
perfil = ExUserProfile.objects.get(user=request.user)
prioridad_media = Prioridad.objects.get(prioridad='Media')
estado_abierta = Estado.objects.get(estado='Abierta')
tipo_incidencia = Tipos.objects.get(tipo='Incidencia')
datos_apertura = {'cliente': perfil.user,
'tipo': tipo_incidencia,
'prioridad:': prioridad_media,
'estado': estado_abierta
}
if request.method == 'POST':
form = newincidForm(request.POST,initial=datos_apertura)
if form.is_valid():
tar=form.save(commit=True)
apertura = TipoNota.objects.get(tiponota='Apertura')
anotacion = Nota(numtar=tar, tiponota=apertura,
anotador=perfil.user,
contenido='Incidencia Abierta')
anotacion.save()
else:
form = newincidForm(initial=datos_apertura)
return render(request, "incid/newincid.html", {'form':form})
with this form:
class newincidForm(ModelForm):
class Meta:
model = Tarea
exclude = ['numtar', 'creacion', 'revision', 'cierre']
def __init__(self, *args, **kwargs):
super(newincidForm, self).__init__(*args, **kwargs)
self.fields['descorta'].widget.attrs['class'] = 'form-control no-resize'
self.fields['deslarga'].widget.attrs['class'] = 'form-control no-resize autogrowth'
and this template:
{% extends "incid/base_incid.html" %}
{% load bootstrap3 %}
{% load static %}
{% load logo %}
{% load i18n %} <!-- Hooks para poder hacerlo multilingüe -->
{% load tags_html %}
{% block css %}
{% bootstrap_css %}
{% bootstrap_javascript %}
<link rel="stylesheet"
href="{% static 'adminbsb/plugins/jquery-datatable/skin/bootstrap/css/dataTables.bootstrap.css' %}"/>
{% endblock %}
{% block content %}
<div class="container-fluid">
<div class="row clearfix">
<h4 style="margin-bottom: 10px; margin-top: 10px; padding-left: 15px">NUEVA INCIDENCIA</h4>
</div>
<div class="body">
<form action= "{% url 'incid:newincid' %}" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
{{ form.errors }}
</div>
</div>
{% endblock %}
extending a standard base with no references to either prioridad, tipo or estado.
Nevertheless, when rendered, tipo and estado show the initial values but prioridad doesn't. I have rewritten view, form and template from scratch twice as I couldn't find a typo but it still happens. I would appreciate any clues or hints on what to do.
Note: This is a revisitation of another problem I posted that I do not know how to delete or edit.
Forget about it. It was something as silly as that I had included the semicolon into the quotes in the datos_apertura definition:
It was written this way:
'prioridad:': prioridad_media,
when it should have been
'prioridad': prioridad_media
Several days lost in such idiocy. An error should raise if I try to initiate an unknown field of a form ,Shouldn't it?. Also if PyCharm didn't take every thing as typos I wouldn't have had it silenced.
Thanks a lot and thanks for the patience in reading my posts.

nothing is displayed on the page with all products in Django

There is a model with three classes of category-subcategory-products
class Category(models.Model):
name_category = models.CharField(verbose_name = 'name cat', max_length = 100, null=True)
image = models.ImageField(null=True, blank=True, upload_to="media/", verbose_name='pic')
slug = models.SlugField(max_length=160, unique=True, null=True)
def __str__(self):
return self.name_category
class Subcategory(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='категория', related_name='sub')
name_subcategory = models.CharField(verbose_name = 'name subcat', max_length = 100, null=True)
image = models.ImageField(null=True, blank=True, upload_to="media/", verbose_name='pic')
slug = models.SlugField(max_length=160, unique=True, null=True)
def __str__(self):
return self.name_subcategory
class Product(models.Model):
subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE, verbose_name='категория',related_name='prod')
name_product = models.CharField(verbose_name = 'name product', max_length = 100, null=True)
image = models.ImageField(null=True, blank=True, upload_to="media/", verbose_name='pic')
price = models.IntegerField('price')
def __str__(self):
return self.name_product
views.py
class CategoryView(ListView):
"""all category"""
model = Category
class CategoryDetailView(DetailView):
"""all sub category"""
model = Category
class SubcategoryView(ListView):
"""all product"""
model = Subcategory
url.py
urlpatterns = [
path("", views.CategoryView.as_view()),
path('<slug:slug>/', views.CategoryDetailView.as_view(), name='category_detail'),
path('<slug:slug>/<slug:slug_sub>/', views.SubcategoryView.as_view(), name='subcategory_list'),
]
page template from which I go to the page with all products (category_detail.html)
{% extends 'base.html' %}
{% block content %}
<h2>{{ category.name_category }}</h2>
{% for sub in category.sub.all %}
{{sub.name_subcategory}}
<img src="{{sub.image.url}}" width="100px" height="100px">
{% endfor %}
{% endblock %}
page template (subcategory_list.html) with all products (here I did not write the output of the products because even the name of the subcategory is not transmitted)
{% extends 'base.html' %}
{% block content %}
{{sub.name_subcategory}}
{% endblock %}
I just can’t understand why it doesn’t display anything on the last page. Perhaps the problem is in the classes in views since previously tried to write only through functions
By default, on DetailView, Django sends an object to the context and therefore that's what you should access in your template. You can see it here
{% extends 'base.html' %}
{% block content %}
<h2>{{ object.name_category }}</h2>
{% for sub in object.sub.all %}
{{ sub.name_subcategory }}
<img src="{{ sub.image.url }}" width="100px" height="100px">
{% endfor %}
{% endblock %}
You also will need a SubCategoryDetailView if you want to see details of that. If you want to override how Django passes data to the context, you can declare context_object_name with whatever you like. Please also have a look here

Problem with the presentation of data from the database on the html page in Django

I have a problem creating something like this in the html file, of course based on the data from the database and using loop:
Cycle_title1
post_title1
post_title2
post_title3
Cycle_title2
post_title1
post_title2
post_title3
where post_title are post titles which was added to subsequent cycles
I tried do it in this way, but it return only one set of titles:
#views
cycles = Cycle.objects.filter(author=user)
for cycle in cycles:
c_post = Post.objects.filter(cycle__title__startswith=cycle.title)
context = {
'posts': posts,
'user': user,
'u_form': u_form,
'p_form': p_form,
'cycles': cycles,
'c_post': c_post,
}
print(c_post)
return render(request, 'users/profile.html', context)
#html
{% for cycle in cycles %}
<h4>{{cycle.title}}</h4>
{% for c in c_post %}
<h5>{{ c.title }}</h5>
{% endfor %}
{% endfor %}
#my_models:
class Post(models.Model):
title = models.CharField(max_length=50, unique=True)
content = MDTextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class Cycle(models.Model):
title = models.CharField(max_length=200, unique=True)
description = models.TextField(max_length=500, default="Brak opisu")
date_created = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
posts = models.ManyToManyField(Post)
Of course you'll only get one set of posts, you keep resetting the c_post variable each time over the loop so you'll just end up with the one from the last iteration.
You shouldn't be doing this in the view at all. You should do it in the template. Plus, you shouldn't be doing that strange filtering on title__starts_with; you should just follow the relation.
{% for cycle in cycles %}
<h4>{{cycle.title}}</h4>
{% for c in cycle.posts.all %}
<h5>{{ c.title }}</h5>
{% endfor %}
{% endfor %}

query and display the data in template

models.py
class ReportType(models.Model):
report = models.ForeignKey(Report)
title = models.CharField('Incident Type', max_length=200)
type = models.ForeignKey(Types, null=False, default=False)
class Types(models.Model):
user = models.ForeignKey(User, null=True)
title = models.CharField('Incident Type', max_length=200)
parent_type_id = models.CharField('Parent Type', max_length=100, null=True, blank=True)
is_active = models.BooleanField('Is Active', default=True)
views.py
def method(request):
report_types = ReportType.objects.filter(report=int(report_id)).select_related("type")[:3]
return{'what_tab': report_types,}
template.html
{% if leftbar.what_tab.0.type.title%}{{ leftbar.what_tab.0.type.title}}{%endif%}
I am storing the integer value in type column in ReportType model.
I am able to display the 1st item alone into template.I don't know how to display all the saved item into template.
Need help.
Thanks
I dont know what leftbar is, but assuming you got all the other stuff right,
{% for tab in leftbar.what_tab %}
{% if tab.type.title %}
{{ tab.type.title}}
{% endif %}
{% ifnotequal forloop.counter leftbar.what_tab %},{% endnotifequal %}
{% endfor %}
Since title is not nullable, {% if tab.type.title %} should never be the case.