Django 1.8 calls to database in html code - python

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 %}

Related

How can I loop through dynamic URLs in Django 4?

The problem:
I recently published a site on Python Anywhere and had to go through the tedious process of changing all of the page URLs I had set through my SQLite database. All of the URLs were broken since the root had changed from the local port to "username.pythonanywhere.com".
I had no problem doing this, but I realized that in order to do local development I would need to change the URLs in the database back to their local port paths. This is obviously why we use dynamic URLs. However, the URLs that were hard coded were like that because I was using a for loop on the rendered html page to loop through those static URLs in my database.
My question is, how can I use dynamic URLs {% url app:template %} in a for loop? Ideally, I would like to have a field in my database that contains the app:template information such that I can loop through all the projects in my database and link them dynamically by grabbing the info from that field.
I have tried creating a new CharField in models.py with a string value for {% url app:template %}, hoping that it would work with the templating language of href="{{ project.href_str}}", but this doesn't seem to work. I have tried this method in various combinations of field string values and templating language values. I also tried this method of using the templating language as a string by adding a dictionary to my views.py return statement, with the difference of calling the keys in href="{{ project_urls.appname }}". No luck here either.
Just for the record, I have tried the dynamic URLs that I want outside of loops and they work perfectly, so I don't think this is a problem with the url mapping itself.
Here's the HTML:
In my database, project.href_str has a value of {% url 'calculator:calculator' %}
{% for project in projects %}
<div class="col-lg-3 col-md-6">
{% if project.href_str %}
<a href="{{ project.href_str }}" target="_blank">
<img src="{{ project.image.url }}" class="img-fluid mb-2" style="">
</a>
{% else %}
<img src="{{ project.image.url }}" class="img-fluid mb-2" width="500" height="500">
{% endif %}
<h3 class="">{{ project.title }}</h3>
<p>{{ project.description }}</p>
</div>
{% endfor %}
Answering my own question. All I needed to do was reference the model field without any templating language.
<a href="{% url project.href_str %}" target="_blank"> where project.href_str is a CharField works perfectly fine. My problem was assuming it needed {{}} or something extra.
{% for project in projects %}
<div class="col-lg-3 col-md-6">
{% if project.href %}
<a href="{% url project.href_str %}" target="_blank">
<img src="{{ project.image.url }}" class="img-fluid mb-2" style="">
</a>
{% else %}
<img src="{{ project.image.url }}" class="img-fluid mb-2" width="500" height="500">
{% endif %}
<h3 class="">{{ project.title }}</h3>
<p>{{ project.description }}</p>
</div>
{% endfor %}

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

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

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

Django templatetags rendered as None in the template

Somebody can help me how to solve this problem, why my templatetags isn't rendered in the template? but, only rendered as None instead.
Previously I working with Django==1.10.4.
1. templatetags/total_tags.py, I already created __init__.py inside this folder.
from django import template
from myapp.models import Category
register = template.Library()
#register.simple_tag
def total_categories():
"""
{% load total_tags %}
{% total_categories %}
used in: `includes/menus_dashboard.html`
"""
print(Category.objects.all()) # this worked well
Category.objects.all().count()
2. myapp/dashboard.html
{% extends "base.html" %}
{% load i18n %}
{% block title %}{% trans "Dashboard" %} :: {{ block.super }}{% endblock %}
{% block content %}
<div class="ui two column stackable grid">
<div class="four wide column dashboard-menu">
{% include "includes/menus_dashboard.html" %}
</div>
</div>
{% endblock %}
3. includes/menus_dashboard.html
The templatetags of {% total_topics %} is similiar with {% total_categories %}
{% load total_tags %}
<div class="ui fluid large inverted vertical pointing menu">
<a class="active item">
Dashboard
</a>
<a class="item">
Categories <div class="ui small label">{% total_categories %}</div>
</a>
<a class="item">
Topics <div class="ui small label">{% total_topics %}</div>
</a>
<a class="item">
Moderators <div class="ui small label">2</div>
</a>
<div class="item">
<div class="ui icon input">
<input type="text" placeholder="Search threads...">
<i class="search icon"></i>
</div>
</div>
</div>
Another idea, I tried like this answer: https://stackoverflow.com/a/12143011. and handle it with #register.assignment_tag, but still doesn't work well and only None instead.

Using Django numeric variable in css

I'm trying to get a bootstrap progress bar to work, but I'm running into a problem. I want to get the progress bar width from a Django variable, I use the templates language for this. The problem is, HTML changes the float variable (i.e 32.54) to a string (i.e 32,54). I'm not sure why this happens (my guess is encoding) but the width attribute will not work if the variable is not a number.
To clarify, this is my code.
Views.py:
def details(request):
estudio = request.GET.get('estudio', '')
uni = request.GET.get('uni', '')
campus = request.GET.get('campus', '')
result = Titulaciones.objects.raw('SELECT * FROM tasas t INNER JOIN titulaciones tit on t.codigo_titulacion = tit.codigo_titulacion INNER JOIN impartida_en imp ON tit.codigo_titulacion = imp.codigo_titulacion INNER JOIN centros cent ON imp.codigo_centro = cent.codigo_centro WHERE cent.universidad = %s and tit.nombre = %s and cent.campus =%s', [uni, estudio, campus]);
return render(request, 'proyecto_uni/details.html', {'result':result})
(If I print here, the variable still shows as a number).
details.html:
{% extends "base.html" %}
{% block content %}
{% for foo in result %}
<ul class="nav nav-tabs">
<li role="presentation"><a href="#tab1" >General</a></li>
<li role="presentation">Asignaturas</li>
<li role="presentation">Resultados</li>
</ul>
<!-- TAB 1 -->
<div id="tab1">
<div class="panel panel-primary">
<!-- Default panel contents -->
<div class="panel-heading">{{foo.nombre}}</div>
<div class="panel-body">
<h4>Universidad:</h4>
<p>{{ foo.universidad }}</p>
<hr class="m-y-2">
<h4>Campus:</h4>
<p>{{ foo.campus }}</p>
<hr class="m-y-2">
<h4>Descripción:</h4>
<p>Aquí debería ir la descripción</p>
<hr class="m-y-2">
<h4>Nota de corte:</h4>
<p>{{ foo.nota_corte }}</p>
</div>
</div>
</div>
<!-- TAB 2 -->
<div id="tab2">
<p>tab2</p>
</div>
<!-- TAB 3 -->
<div id="tab3">
<div class="panel panel-primary">
<div class="panel-heading">{{foo.nombre}}</div>
<div class="panel-body">
<div class="progress">
<div class="progress-bar progress-bar-success" style="width: {{foo.rendimiento}}%">
<span class="sr-only">{{foo.rendimiento}}% Complete (success)</span>
<!-- The problem is right above, in the width style tag -->
</div>
<div class="progress-bar progress-bar-warning" style="width: 2%">
<span class="sr-only">22% Complete (warning)</span>
</div>
<div class="progress-bar progress-bar-danger" style="width: 1%">
<span class="sr-only">1% Complete (danger)</span>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% endblock%}
I posted all the code to make it easier to understand, hope I didn't make it more confusing. Anyways, thanks in advance!
Django formats numbers according to your localization settings. You can turn localization off by using:
{% load l10n %}
{% localize off %}
{{ foo.rendimiento }}
{% endlocalize %}
You can also unlocalize one single value:
{% load l10n %}
{{foo.rendimiento|unlocalize}}
Django format localization documentation

Categories