How can I loop through dynamic URLs in Django 4? - python

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

Related

How to insert images from render( , , context) in Django?

guys! New in Django so maybe it's a silly question. I have a .json file that keeps information about shop's clothes including "img". The goal is to otput all the information about products in a single "for loop". So I've written such lines
{% for product in products %}
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<a href="#">
<img class="card-img-top"
src="{% static '{{ product.img }}' %}" !!! problem is here
alt="">
</a>
<div class="card-body">
<h4 class="card-title">
{{ product.name }}
</h4>
<h5>{{ product.price }}</h5>
<p class="card-text"> {{ product.description }}</p>
</div>
<div class="card-footer text-center">
<button type="button" class="btn btn-outline-success">Отправить в корзину</button>
</div>
</div>
</div>
{% endfor %}
Everything works fine except the line concerns an image. In devtools I get the next path "/static/%7B%7B%20product.img%20%7D%7D". But in the .json file it looks like "img": "vendor/img/products/Brown-sports-oversized-top-ASOS-DESIGN.png". I am totally confused about that situation and definitely in a bind. I appreciate any help
work with:
<img src="{{ product.img.url }}">
if the image is effective (product.img is not None), and you added the media urls to the urls.py, then it will determine the URL where to fetch the product image.
Note that in production, Django does not serve media files, so in that case you will need to configure the webserver (Apache, Nginx, etc.) to serve media files for you.

How to display the search result score as percentage in the frontend?

I've recently set up Elasticsearch on my Django project using Django-haystack and I want to display the search results' scores as percentages in my templates (html).
So I am wondering if there's a way to achieve this?
A quick example of the final result would be this:
<div>
{% if page_obj.object_list %}
<ol class="row top20">
{% for result in page_obj.object_list %}
<div class="showcase col-sm-6 col-md-4">
<!-- Matching score to be displayed in the h5 below -->
<h5>{{result.object.matching_score}}</h5>
<a href="{{ result.object.get_absolute_url }}">
<h3>{{result.object.title}}</h3>
<img src="{{ result.object.image }}" class="img-responsive">
</a>
</div>
{% endfor %}
</ol>
{% endif %}
</div>
I'm still new to this but maybe an If - Else statement, the Elasticsearch default _score value or even some Javascript might do the job. I'm not sure, so what do you think I should do?
If matching_scroe is what you want to show as a percentage you can do it using {{result.object.matching_score|floatformat:2}}%
If you have 2 values that need dividing you need to write a template tag
In directory templatetags, mytags.py
from django import template
register = template.Library()
#register.filter
def div(numerator, denominator):
return float(numerator/denominator)
In your html file
{% load mytags %}
{{ object.numerator|div:object.denominator }}%

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

Python code between django "autoescape off" marks can not be executed

I am trying to establish a blog using Django. I directly stored HTML into models. And I used {% autoescape off %} and {% endautoescape %} marks in HTML files that tells Python do not autoescape HTML code to string. Between the marks, I used codes like {{ article.content }} to load HTML codes stored in models.
The problem is that <img src="{% static 'img/dot.png' %}"> (HTML codes stored in models) will be displayed as {%%20static%20'img/dot.png'%20%}. The python codes won't be executed.
I feel helplessness. Does anyone have a good idea?
Here is a example of one template:
{% extends "base.html" %}
{% block content %}
{% load static %}
<div style='margin:0 auto;width:0px;height:0px;overflow:hidden;'>
<img src="{% static 'img/wechat.png' %}">
</div>
<header>
<div id="logo">
<span class="heading_desktop">You are browsing </span>Paradox<span class="heading_tablet"> , a personal site</span><span> of </span>Jiawei Lu<span class="heading_tablet"> since 2015</span><span class="phone_h">. Happy<script>document.write(" " + whatDay());</script>.</span>
</div>
<nav>
<ul>
<li>Articles</li>
<li>Portfolio</li>
<li>Jiawei Lu</li>
</ul>
</nav>
<hr class="red">
</header>
<div id="breadcrumb" class="article">
Articles → {{ article.title }}
</div>
<div id="wrapper">
<article>
<h1 class="article">{{ article.title }}</h1>
<div id="post_info">
<p>Published on {{ article.timestamp }}<!--<span> | </span>--></p>
<!-- Category inside article <p>Category 1Category 2<span> | </span></p> -->
<!-- Share inside article <p>Share: Email/Linkedin</p> -->
</div>
<div id="post_content" class="article">
{% autoescape off %}
{{ article.content }}
{% endautoescape %}
</div>
</article>
</div>
</div>
{% endblock %}
article.content: HTML Codes, like
<h1>Test</h1>
<img src="{% static 'img/dot.png' %}">
This doesn't really have anything to do with autoescaping. When Django outputs a variable, it doesn't do anything to interpret whatever is in that variable; so putting template tags into a model field won't work.
You would need to do something to render that data yourself manually; perhaps a custom template tag, or a model method, that uses the Template API to instantiate a template object and call its render method.

Categories