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

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.

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

How to create a dynamic bootstrap carousel, using flask/python?

For context:
I'm building a social network. Just like with Facebook, each profile has a tab titled "images", which is a collection of thumbnails from the profile owner's posts.
My goal:
Just like with Facebook, I'd like the user navigating the page to be able to click on any thumbnail image, launching a bootstrap carousel and displaying that specific image in a much larger view. The user could then use the carousel-control class to scroll through the profile owner's other images.
Current situation:
The thumbnails display, you can click on any thumbnail and launch the carousel, but all of the profile owner's images appear stacked, as if they're all active.
I'm using a jinja2 for loop and a url_for statement to access the images. I also use a loop counter within an if statement to make it so only one image is active, but its obviously not working :(
It was this 4 year old stackoverflow post that I used to attempt solving this problem to begin with.
When using the carousel with a few images added statically it works properly, but I need it to be dynamic for obvious reasons.
I'm unsure how to go about showing just the specific image that was clicked on, and having the ability to scroll through the others.
Any help will be greatly appreciated!
Here is my HTML
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
{% for post in user.posts %}
{% if post.post_img != None %}
<div class="container">
<div class="item {% if loop.counter == 1 %} active {% endif %}" id="slide{{ loop.counter }}">
<img src="{{ url_for('static', filename='post_pics/' + post.post_img) }}">
</div>
<a class="carousel-control-prev" href="#pageCarousel" role="button" data-slide="prev">
<span class="carousel-control-prev-icon bg-primary" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#pageCarousel" role="button" data-slide="next">
<span class="carousel-control-next-icon bg-primary" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
{% endif %}
{% endfor %}
</div>
</div>
You can move the a tags outside the inner-carousel div, maybe like below ( its untested)
If you look at the documentaion, the a tags have to be outside.
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
{% for post in user.posts %}
{% if post.post_img != None %}
<div class="carousel-item {% if loop.index == 1 %} active {% endif %}" id="slide{{ loop.index }}">
<img src="{{ url_for('static', filename='post_pics/' + post.post_img) }}">
</div>
{% endif %}
{% endfor %}
</div>
<a class="carousel-control-prev" href="#pageCarousel" role="button" data-slide="prev">
<span class="carousel-control-prev-icon bg-primary" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#pageCarousel" role="button" data-slide="next">
<span class="carousel-control-next-icon bg-primary" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>

How to use Django for loop twice on the same data

I'm attempting to use a for loop to iterate over the same data twice in the same Django template. However the second for loop only returns the first object in the database.
Basically I have an image of each job in the database on the homepage and when clicked on it should display a more detailed description of that job. All the jobs from the database display fine on the homepage but they all display the description of the first job when clicked on.
I think it's something to do with only being able to use an iterator once but I can't figure out what the solution is.
model.py
from django.db import models
class Job(models.Model):
title = models.CharField(max_length=50, default="Example Work")
image = models.ImageField(upload_to='images/')
summary = models.TextField()
views.py
from django.shortcuts import render
from .models import Job
def get_index(request):
jobs = Job.objects
return render(request, 'index.html', {'jobs': jobs})
index.html
{% for job in jobs.all %}
<div class="col-md-6 col-lg-4">
<a class="portfolio-item d-block mx-auto" href="#portfolio-modal">
<div class="portfolio-item-caption d-flex position-absolute h-100 w-100">
<div class="portfolio-item-caption-content my-auto w-100 text-center text-white">
<i class="fas fa-search-plus fa-3x"></i>
</div>
</div>
<img class="img-fluid" src="{{ job.image.url }}" alt="">
</a>
<h3 class="text-center text-secondary">{{ job.title }}</h3>
</div>
{% endfor %}
<!-- Portfolio Modal -->
{% for job in jobs.all %}
<div class="portfolio-modal mfp-hide" id="portfolio-modal">
<div class="portfolio-modal-dialog bg-white">
<a class="close-button d-none d-md-block portfolio-modal-dismiss" href="#">
<i class="fa fa-3x fa-times"></i>
</a>
<div class="container text-center">
<div class="row">
<div class="col-lg-8 mx-auto">
<h2 class="text-secondary text-uppercase mb-0">{{ job.title }}</h2>
<hr class="star-dark mb-5">
<img class="img-fluid mb-5" src="{{ job.image.url }}" alt="Image of website">
<p class="mb-5">{{ job.summary }}</p>
<a class="btn btn-primary btn-lg rounded-pill portfolio-modal-dismiss" href="#">
<i class="fa fa-close"></i>Close Project</a>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
Just for context, I've ripped out a lot of the html code from index.html because that all works fine and it probably isn't relevant. I've tried it in within one loop which doesn't work either. The description opens up within a new window on the same page. I've tried anything I can think of but not getting anywhere with it. Still getting to grips with Django and Python. Any help appreciated.
This isn't anything to do with Django outputting the same data for each iteration. If you check the generated HTML via View Source in your browser, you'll definitely see the correct data.
The problem is with your HTML itself. You cannot have multiple elements with the same HTML id attribute; but you are using id="portfolio-modal" for each one. When your JS tries to pop up the modal, it will only ever find the first instance of this ID.
You need to use a different ID in each iteration - perhaps by appending a unique element, eg the Job pk - and/or use a class to trigger your modal.

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

Categories