Getting a total number of objects inside each object using django markup - python

Using Django, I am trying to output the total number of lots in each community.
A community has several lots, and there are several communities. Here is an example of what I am getting:
Total lots: 99.
This community only has 2 lots. There are 4 communities with a total of 9 lots between them.
The models and views seem correct. Is there a filter I am missing or a different way of writing this to get the correct result?
{% if community.is_active %}
<a class="panel-link" href="{% url 'community-detail' pk=community.id %}" %}>
<div class="col-md-6 community_col">
<div class="community_box">
<div class="row">
<br>
<div class="col-md-4 community_img">
<img src="/media/{{ community.logo }}" alt="">
</div>
<div class="col-md-7 col-md-offset-1">
<h1 style="margin-bottom: -10px; margin-top: -15px;"><small>{{ community.name }}</small></h1>
<h4>{{ community.city }}, {{ community.state }}</h4>
<h6>Total lots: {% for lot in community.lot_set.all %}{{ lots|length }}{% endfor %}</h6>
<h6>Total Active lots: </h6>
<h6>Total Sold lots: </h6>
<h6>Total Inactive lots: </h6>
</div>
</div>
</div>
</div>
</a>
{% endif %}
{% endfor %}

This logic:
{% for lot in community.lot_set.all %}{{ lots|length }}{% endfor %}
Iterates through each lot object. You then take the length of lots which as far as I can tell is not a variable in context. If you wanted to just count the objects:
{{ community.lot_set.count }}
would do.
Looking ahead though, you're going to want to get counts of Active, Sold, Inactive, etc, and to do this efficiently you should look into annotating the queryset and doing this counting in the database:
https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset

Related

Django Web Development

I am a beginner in python and django and im practicing making a website for selling stuff. I am in the part where I am supposed to edit a card from bootstrap with the attributes from my models.py that is also in the views.py as a function.
This is the html:
(the 'base.html' is the starting template from bootstrap)
{% extends 'base.html' %}
{% block content %}
<h1>Products</h1>
<div class="row">
{% for product in products_dict %}
<div class="col">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="{{ product.image_url }}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ product.name }}</h5>
<p class="card-text">{{ product.price }}</p>
Add to cart
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
This is the result that i get:
[As you can see the cards just keep on stacking to the right and decrease in size, it does not come down.]
Can anyone help me with this? Please tell if I need to share more info on this.
https://i.stack.imgur.com/sXQXr.jpg

How do I hide or show content for each iteration?

I have a Lecture model which contains lectures. For each lecture I have a title and a content and eventually some files. I was trying to make that when somebody presses on a title, the title and the content will display under, but only for that lecture. Problem is that if I use a class, all lectures will be shown and if I use and id only the first one will be shown. How should I do this ?
$('#title').click(function () {
$('#lecture-hide').toggle();
});
{% for c in category.list %}
<div id="title">
<p>Lecture {{ forloop.counter }}: <span>{{ c.lecture_title }}</span>
</p>
<br>
</div>
<div id="lecture-hide" style="display: none;">
<br>
<li><h5>{{ c.lecture_title }}</h5></li>
<li><p>{{ c.content }}</p></li>
{% for file in c.files.all %}
{% if file.files %}
{% if forloop.first %}
<p id="files">Lecture files:</p>
{% endif %}
<li><a class="media"
href='{{ MEDIA_URL }}{{ file.files.url }}'><i
class="fas fa-download"></i>{{ file.files.name }}</a></li>
{% endif %}
{% endfor %}
<br>
</div>
{% endfor %}
Maybe you can use next selector in your jQuery code like this:
$('div.title').click(function () {
$(this).next().toggle();
});
You have to change id of the title to class to apply this to every element of the list.
You need to set dynamic attributes in your html:
{% for c in category.list %}
<div class="title" id="title-{{ c.id }}">
<!-- the content -->
</div>
<div class="lecture-hide" for="title-{{ c.id }}" style="display: none;">
<!-- the content -->
</div>
{% endfor %}
and in JQuery
$('.title').click(function () {
$('.lecture-hide[for="title-' + $(this).attr('id') + '"]').toggle();
});
This will works even if the html elements order change.

How to avoid repetition on templates in Django? [duplicate]

This question already has answers here:
How to make a reusable template in Django?
(8 answers)
Closed 5 years ago.
I have the following code that is repeated on several templates:
{% for element in elements %}
<div class="some-class">
<div class="another-class">
<div class="row">
<div class="col-xs-3">
<img class="img-responsive" alt="{{ entry.user }} avatar" style="border-radius: 50%; width: 100%;" src="{{ entry.avatar_url}}">
</div>
<div class="col-xs-9" style="some-style">
{% if entry.data1 %}<small>{% trans entry.data1 %}</small><br>{% endif %}
{% trans entry.data2 %} {% trans entry.data2 %}
<br>
<small style="some-style">
{% blocktrans with timestamp=entry.timestamp|naturaltime %}
{{ timestamp }}
{% endblocktrans %}
</small>
</div>
</div>
</div>
</div>
{% endfor %}
I was wondering what is the best way to avoid repeating this piece of code, I am kind of newbie to Django, and I would really appreciate your help.
Edit:
What if I need to pass a content to that template. Is it going to use the same context than the one in the containing file or should I indicate the context in some way?
That is easy:
Put this piece of HTML in a file called, say reusable.html and then include it in other templates.
Like this:
<!-- Other HTML -->
... html stuff here
{% include 'reusable.html' %}
Now, if you want to pass a parameter to reusable.html, you do it like this:
`{% include 'reusable.hmtl' with var_a='abc' var_b=123 %}`
Set it up in it's own template, for example new_template.html and use {% include 'new_template.html' %} wherever you want it

Django 1.8 calls to database in html code

long-time lurker for this website, but I finally decided to join the community.
I have a quick question on some of my code. I took a job this year for my university developing a website for the journalist department. The website was being built the previous year by another student using Django 1.8, python 2, and everything else that comes with that. I knew a decent amount about these languages, and I have learned a lot testing out different methods for hours on end. However, there is one thing I am having trouble with that I have researched for forever.
Basically, for my website, I have different "sections" for different pages of articles. These articles have many traits. One trait is called "section" and this section has the names of the pages. So for example:
One page is named "look". I can call my code and display all of my featured_articles. HOWEVER, I am trying to only display the articles where the name of the section equals "look".
Here is my current code. Any ideas? I have tried many things but I can't get it to work properly. For loops, if statements, different HTML processes, different pages in django, etc...
{% for article, section in featured_articles %}
<div class="media panel panel-default">
<div class="panel-body">
<div class="media-left">
<a href="articles/{{ article.url }}">
<img class="media-object thumbnail-featured"
src="{{ article.image }}">
</a>
</div>
<div class="media-body">
<a href="articles/{{ article.url }}">
<h3 class="media-heading">{{ article.title }}</h3>
</a>
<!-- TODO figure out how to iterate through the authors field, manytomany -->
{% for contributor in article.authors.all %}
<p>{{ section.name }} |
{{contributor}}</p>
{% endfor %}
<p>{{article.preview}}</p>
</div>
</div>
</div>
{% endfor %}
Thank you for any help!!
Overall, it is a not such a good idea. You are sending all data to the template engine and doing the filtering there?
Why not filter it in the view function / view class and then return that data inside a template variable and then render in the front end?
def detail(request, poll_id):
filtered_data = .......objects.get(name='look')
return render(request, 'polls/detail.html', {'look_data': filtered_data})
{% for article, section in look_data %}
<div class="media panel panel-default">
.... blah blah blah
</div>
{% endfor %}
As I understand, you just need to add if statement:
{% for article, section in featured_articles %}
{% if section.name == 'look' %}
<div class="media panel panel-default">
<div class="panel-body">
<div class="media-left">
<a href="articles/{{ article.url }}">
<img class="media-object thumbnail-featured"
src="{{ article.image }}">
</a>
</div>
<div class="media-body">
<a href="articles/{{ article.url }}">
<h3 class="media-heading">{{ article.title }}</h3>
</a>
<!-- TODO figure out how to iterate through the authors field, manytomany -->
{% for contributor in article.authors.all %}
<p>{{ section.name }} |
{{ contributor }} </p>
{% endfor %}
<p>{{article.preview}}</p>
</div>
</div>
</div>
{% endif %}
{% endfor %}

jijna2 for loop variable preservation?

I'm working on a web app and trying to add functionality where you make an anonymous post and then someone can add an answer to it. I'm using Flask for backend. I have the posts stored in an SQLAlchemy database. By default, a post doesn't have an answer. To dispay the posts, I just print each one with a for loop using jinja2. In that for loop, I also print an "answer" button after each post that brings up a Foundation modal that is supposed to let the user enter their answer. The problem is that the action attribute references the post ID ({{post.id}}), which by the end of the loop refers to the last post. Here's my code:
{% for post in s: %}
{% if post.nh == hood %}
<li>
<td> {{ post.date.strftime('%Y-%m-%d %H:%M:%S') }} </td>
<br>
<td> {{ post.text }} {{post.nh}} </td>
<br>
Answer
<div id="reply_modal" class="reveal-modal" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog">
<p>{{ post.text }}</p>
<form action='/{{post.id}}/{{hood}}' method="post">
<div class="row">
<div class="large-12 columns">
<textarea placeholder="Write your answer here"name="user_input" required></textarea>
</div>
<div class="right">
<button type="submit">Submit</button>
</div>
</div>
</form>
<a class="close-reveal-modal" aria-label="Close">×</a>
</div>
<br>
{% if post.answer != 'none' %}
<li>
<div align="right">
<td> {{ post.answer }} </td>
</div>
</li>
{% endif %}
</li>
{% endif %}
{% endfor %}
I basically need to preserve {{post.id}} for each "answer" button so that the answer gets added to the correct post. I would appreciate any suggestions.

Categories