Rendering queryset on template without <QuerySet [<User:>]> - python

I am rendering a ManyToManyField in my template but it is shown like this :
<QuerySet [<User: Guido>]>
And I just want to print out the username without the function.
My views.py
class HotelListView(LoginRequiredMixin,ListView):
model = Hotel
def get_queryset(self):
return self.model.objects.filter(collaborateurs=self.request.user)
My template
{% for Hotel in object_list %}
{{ Hotel.collaborateurs.ALL }}
{% endfor %}
Thanks.
Edit
Models.py
class Hotel(models.Model):
collaborateurs = models.ManyToManyField(User, verbose_name="Liste des collaborateurs autorisés")
code = models.CharField(max_length=500,verbose_name="Code hôtel", null=True, blank=True)
email_manager = models.EmailField(max_length=150,verbose_name="Contact RH", null=True, blank=True)
contact_rh = models.EmailField(max_length=150,verbose_name="Contact RH", null=True, blank=True)
contact_gm = models.EmailField(max_length=150,verbose_name="Contact GM",null=True, blank=True)
payday = models.CharField(max_length=500,verbose_name="Jour de paye prévu du mois", null=True, blank=True)
hotel = models.CharField(max_length=500,verbose_name="Nom de l'hôtel")
planning = models.URLField(max_length=500, verbose_name="Planning du mois", null=True, blank=True)
def __str__(self):
return self.hotel
def get_absolute_url(self):
return reverse('hotel')

You need to iterate through the collaborators as well.
{% for Hotel in object_list %}
{% for collaborator in Hotel.collaborateurs.all %}
{{ collaborator.name }}
{% endfor %}
{% endfor %}
(Obviously replace name with the relevant field from the model.)

Related

how to use Exists and OuterRef in prefetch_related in Django?

I have 3 models and I need to display the area and need items only if there is at least 1 product connected. If there are no products in particular Area and Need models then it should not appear in my HTML file.
I have checked the documentation and several answers related to this topic but I cannot implement it in my script.
I also tried to create my custom filter so I can apply it directly in my template but nothing worked.
My problem is that I am getting the list of all items from Need model and I don't know how to exclude empty items from HTML page.
I will appreciate any help.
models.py
class Area(models.Model):
title = models.CharField(max_length=75, blank=False)
body = models.CharField(max_length=150, default='-', blank=False)
publish = models.DateTimeField('publish', default=timezone.now)
class Need(models.Model):
title = models.CharField(max_length=75, blank=False, null=False, help_text='max 75 characters')
body = models.CharField(max_length=150, default='-', blank=False)
publish = models.DateTimeField(default=timezone.now)
need_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='need_area')
class ProductCategory(models.Model):
title = models.CharField(max_length=400, blank=False, null=False, help_text='max 400 characters')
body = models.TextField(default='-')
publish = models.DateTimeField('publish', default=timezone.now)
category_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='category_area', null=True)
category_need = models.ForeignKey(Need, on_delete=models.CASCADE, related_name='category_need', null=True)
class Product(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=400, blank=False)
category = models.ForeignKey(ProductCategory, on_delete = models.CASCADE, blank=True, related_name='products')
status = models.IntegerField(choices=STATUS, default=0)
def get_absolute_url(self):
return reverse("product", kwargs={'slug': self.slug})
views.py
class Search(ListView):
template_name = 'search.html'
model = Product
queryset = Product.objects.filter(status=1)
def get_context_data(self, **kwargs):
context = super(Search, self).get_context_data(**kwargs)
filter_need = Area.objects.filter(Exists(Need.objects.filter(need_area=OuterRef('pk'))))
areas = Area.objects.prefetch_related(Prefetch('need_area', queryset=filter_need, to_attr='need_area__category_need__product')).filter(need_area__category_need__product__status=1).distinct()
context['areas'] = areas
return context
search.html
{% if areas %}
{% for area in areas %}
<div class="border mb-4 pb-4 px-2">
<h2 class="fw-bold my-2">{{area.title}}</h2>
{% for need in area.need_area.all %}
<h4 class="text-muted mt-4">{{need.title}}:</h4>
{% for product_category in need.category_need.all %}
{% for product in product_category.product.all %}
<span class="rounded-pill bg-hubble text-dark f-12 p-2">{{product.title}}</span>
{% endfor %}
{% endfor %}
{% endfor %}
</div>
{% endfor %}
{% endif %}

Running a for loop inside html file for specific time in django

I want a for loop to run 2/3 times for this specific model. Lets assume I have 10 data, I want the first 3 one to be shown inside html file through a for loop. Can anyone help me with this one?
This is the models.py
class CompanyInformation(models.Model):
name = models.CharField(max_length=50)
details = models.TextField(max_length=50)
website = models.CharField(max_length=50, null=True, blank=True)
social_fb = models.CharField(max_length=50, null=True, blank=True)
social_ig = models.CharField(max_length=50, null=True, blank=True)
social_twitter = models.CharField(max_length=50, null=True, blank=True)
social_youtube = models.CharField(max_length=50, null=True, blank=True)
def __str__(self):
return self.name
views.py file
from django.shortcuts import render
from .models import *
# Create your views here.
def aboutpage(request):
aboutinfo = CompanyInformation.objects.all()[0]
context={
'aboutinfo' : aboutinfo,
}
return render(request, 'aboutpage.html', context)
inside the html file
{% block body_block %}
<p class="redtext">{{ aboutinfo.name }}</p>
<p class="redtext">{{ aboutinfo.details }}</p>
<p class="redtext">{{ aboutinfo.website }}</p>
{% endblock body_block %}
Instead of just sending single object through context try sending 3 of them:
company_info_objs = CompanyInformation.objects.all()[:3]
context={
'company_info_objs' : company_info_objs,
}
Then you can loop through them inside the templates as follows:
{% for company_info in company_info_objs %}
<p class="redtext">{{ company_info.name }}</p>
<p class="redtext">{{ company_info.details }}</p>
<p class="redtext">{{ company_info.website }}</p>
{% endfor %}

OperationalError at /1 no such column: auctions_comment.listing_id

I'm new to Django. i'm trying to display all the comments for a listing in an auction site
Help me find a way to display all the comments for a listing.
Mosdels.py
class Listing(models.Model):
title = models.CharField(max_length=64, default="")
starting_bid = models.CharField(max_length=64, default="$")
description = models.TextField(default="")
image_url = models.CharField(max_length=200, default="")
date = models.DateTimeField(default=timezone.now)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default="")
def __str__(self):
return self.title
class Comment(models.Model):
comment = models.TextField(default="")
listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="comments", default="")
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="comments", default="")
def __str__(self):
return f"{self.user} - {self.listing}"
views.py
def listing(request, listing_id):
listing = Listing.objects.get(pk=listing_id)
comments = listing.comments.all()
return render(request, "auctions/listing.html", {
"listing":listing,
"comments":comments
})
_If you are trying to display in a template you can use something like following:
{% for listing_item in listing %}
<div>{{listing_item.title}}
{% for comment in listing_item.comment_set.all %}
<div>{{comment}}</div>
{% endfor %}
</div>
{% endfor %}
EDIT: If only sending the one listing from your view:
{{listing.title}}
{% for comment in listing.comment_set.all %}
<div>{{comment}}</div>
{% endfor %}
EDIT2: Noticed you have a related name there.
{{listing.title}}
{% for comment in listing.comments.all %}
<div>{{comment}}</div>
{% endfor %}

Django template return all files in section

Here my problem, The user can add Sections, in the section he can add documents, what I would like to do it's to return all documents added in section I can't figure it out which way is the best to filter by section:
Here my model for the Documents :
class Document(models.Model):
"""
Staff of the hospital center services
"""
# ATTRIBUTES
label = models.CharField(
max_length=255,
verbose_name='Intitulé'
)
description = models.TextField(
verbose_name='Description',
blank=True,
null=True
)
document = models.FileField(
verbose_name='Document'
)
section = models.ForeignKey(
'espace_documentaire.EspaceDocumentaire',
verbose_name="Espace Documentaire",
related_name="documents",
null=True,
blank=True,
on_delete=models.CASCADE
)
dedicated_page = models.ForeignKey(
"pages.Pages",
verbose_name="Page",
related_name="documents",
null=True,
blank=True,
on_delete=models.CASCADE
)
division = models.ForeignKey(
"services.Division",
verbose_name="Pôle",
related_name="documents",
null=True,
blank=True,
on_delete=models.CASCADE
)
order = models.IntegerField(
verbose_name="Ordre d'affichage",
default=0
)
# TRACE
date_created = models.DateTimeField(
verbose_name="date de création",
auto_now=True
)
date_updated = models.DateTimeField(
verbose_name="date de modification",
auto_now=True
)
def __str__(self):
return self.section
Here my Model for the Sections :
class EspaceDocumentaire(models.Model):
# ATTRIBUTES
section = models.CharField(
max_length=255,
verbose_name='Nom de la section'
)
colorsection = models.CharField(
max_length=255,
verbose_name='Couleur de la section'
)
order = models.IntegerField(
verbose_name="Ordre d'affichage",
default=0
)
document = models.ForeignKey(
'documents.Document',
verbose_name="Document",
related_name="documents",
null=True,
blank=True,
on_delete=models.CASCADE
)
def __str__(self):
return self.section
Here my template :
{% for ed in espace_documentaire %}
<div class="dpt-toggle" id="{{ ed.pk }}">
<h3 class="toggle-title">{{ed.section}}</h3>
<div class="toggle-content">
<div class="tabs clearfix">
{% for document in documents %}
{% if document.section == ed.section %}
<h1>{{ document.label }}</h1>
{% endif %}
{% endfor %}
</div>
</div>
</div>
{% endfor %}
Thanks
Here is how you would filter a single section documents in a view:
def section_documents(request, pk):
section = EspaceDocumentaire.objects.get(pk=pk)
documents = section.documents.all() # using related name you set in your model
return render(request, 'section_documents.html', {'section': section, 'documents': documents})
Then in your template:
{% for document in documents %}
{{ document }}
{% endfor %}
OR you could also just use the related name in the template like this:
def sections_and_documents(request):
sections = EspaceDocumentaire.objects.all()
return render(request, 'sections_and_documents.html', {'sections': sections)
and in the template:
{% for section in sections %}
{{ section }}
{% for document in section.documents.all %}
{{ document }}
{% endfor %}
{% endfor %}

Pagination class based views django 1.5

I'm developing a website based on Django==1.5.7
I need to paginate the ListView of a table in my application.
This is the code i'm using
On models.py:
class UsuarioFidetel(models.Model):
"""
Modelo de usuario fidetel
"""
usuario = models.CharField(max_length=30)
id_usuario = models.IntegerField()
nombre = models.CharField(max_length=255, null=True)
apellido = models.CharField(max_length=255, null=True)
tipo_cedula = models.CharField(max_length=1, null=True)
cedula = models.CharField(max_length=9, null=True)
fecha_nacimiento = models.DateField(null=True, blank=True)
sexo = models.CharField(max_length=1, null=True)
correo = models.EmailField(max_length=254, null=True)
estado_civil = models.CharField(max_length=1, null=True)
def __unicode__(self):
return self.nombre
On views.py:
class UsarioList(ListView):
model = UsuarioFidetel
template_name = 'all_list.html'
On urls.py:
url(r'^usario/$', UsarioList.as_view(model=UsuarioFidetel, paginate_by=2)),
Note the paginate_by attribute of the url, this is working just fine, but when I go to the 2nd page, or whatever page, outside the 1st one, it throws this error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:9001/usario?page=2
All is working fine, but I thought this will pass the page inside the block of my template, without major errors, can't figure out what's wrong here, maybe I need a regex on the url?
Any ideas?
Thanks in advance!
Nevermind, solved it on template, ie:
<span class="page-links">
{% if page_obj.has_previous %}
<
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
>
{% endif %}
</span>
Now it works the way it should

Categories

Resources