I added another div to bottom half of my site but it is not showing up. I can get it to show up in a separate web page, but not when I paste the same code to the bottom of this web page. Check out code, thanks in advance for you efforts.
OK so I understand I need to make "blogs" available in views. I tried modifying the function that defines "blogs", I also tried adding a new function for the page but neither seemed to work. I updated the original post with my views.py.
all_blogs.html
{% extends 'blog/navBarFooter.html' %}
{% block content %}
<br>
<br>
{% for blog in blogs %}
<div class="col-lg-12 col-md-8">
<img src="{{ blog.summaryImage.url }}" height=190 width=350>
<p>{{ blog.category }}</p>
<a href="{% url 'pageOne' blog.id %}">
<h2>{{ blog.title }}</h2>
</a>
<p>By: {{ blog.by }} | {{ blog.date|date:'M d Y'|upper }}</p>
<p>{{ blog.summary }}</p>
<hr color="black">
</div>
{% endfor %}
{% endblock %}
pageOne.html:
{% extends 'blog/navBarFooter.html' %}
{% block content %}
<!-- *************SHOWING UP ON WEBPAGE******************* -->
<h1 class="text-center mt-3" id="blogdetailtitle">{{ blog.title }}</h1>
<h5 class="text-center mt-3" id="blogdetailtitle">By: {{ blog.by }} | {{ blog.category }}</h5>
<hr color="black">
<div class="col-lg-12 col-md-8">
<img id="imgLeft" src="{{ blog.pageOneImage.url }}" height=190 width=350>
<p id="textLeft">{{ blog.pageOne | safe }}</p>
<br>
<br>
<hr>
<img id="imgRight" src="{{ blog.pageTwoImage.url }}" height=190 width=350>
<p id="textLeft">{{ blog.pageTwo | safe }}</p>
<br>
<br>
<hr>
<img id="imgLeft" src="{{ blog.pageThreeImage.url }}" height=190 width=350>
<p id="textLeft">{{ blog.pageThree | safe }}</p>
<br>
<br>
<hr>
<img id="imgRight" src="{{ blog.pageFourImage.url }}" height=190 width=350>
<p id="textLeft">{{ blog.pageFour | safe }}</p>
<br><br><br><br>
<hr>
</div>
<!-- *************NOT SHOWING UP ON WEBPAGE******************* -->
{% for blog in blogs %}
<div class="row">
<div class="col-lg-4 col-md-6">
<img src="{{ blog.summaryImage.url }}" height=190 width=350>
<p>{{ blog.category }}</p>
<a href="{% url 'pageOne' blog.id %}">
<h2>{{ blog.title }}</h2>
</a>
<p>{{ blog.date|date:'M d Y'|upper }}</p>
<p>{{ blog.summary }}</p>
</div>
{% endfor %}
</div>
{% endblock %}
views.py
from django.shortcuts import render, get_object_or_404
from .models import Blog
def all_blogs(request):
blogs = Blog.objects.order_by('category')
return render(request, 'blog/all_blogs.html', {'blogs': blogs})
def pageOne(request, blog_id):
blog = get_object_or_404(Blog, pk=blog_id)
return render(request, 'blog/pageOne.html', {'blog': blog})
def all_blogsT(request):
blogs = Blog.objects.order_by('category')
return render(request, 'blog/pageOne.html', {'blogs': blogs})
Your first half seems to be operating on a single blog variable, and not a list of blogs like in your second half.
So, consider removing the loop from your second half, and it should work.
If this is not the desired output you want, make sure you are using a list of blogs that actually contains elements for your second half. Currently it seems that your list blogs is either undefined or empty.
Related
I have implemented search bar functionality with autocomplete feature. All is good except the fact that in HTML serach results contain multiple the same object. For instance, when I put 2 in my searchbar I see 4 the same in my HTML file. What I want is to get unique objects.
views.py
#login_required
def search_address_qa(request):
query = request.GET.get('title')
payload = []
if query:
lookups = Q(title__icontains=query)
address_objects = Article.objects.filter(lookups)
address_objects_qa = QA.objects.filter(lookups)
for address_object in address_objects or address_objects_qa:
payload.append(address_object.title)
return JsonResponse({'status':200, 'data': payload})
#login_required
def search_articles(request):
query = request.GET.get('q')
article = Article.objects.filter(title__icontains=query)
qa_list = QA.objects.filter(title__icontains=query)
if query is not None:
lookups = Q(title__icontains=query) | Q(tags__name__icontains=query)
article = Article.objects.filter(lookups)
qa_list = QA.objects.filter(lookups)
context = {
'search_articles': article,
'query_name': query,
'qa_list': qa_list
}
return render(request, 'search/search_articles.html', context)
search_view.html
{% extends 'base.html' %}
<title>{% block title %}search results{% endblock %}</title>
{% block search %}
{% include 'main/sidebar.html'%}
<link rel="stylesheet" type="text/css" href="/static/search.css">
<div class="d-flex justify-content-end h-100 pb-4">
<div>
{% if user.is_authenticated %}
<form action="{% url 'search_articles' %}" method="get" id="search">
{% csrf_token %}
<div class="searchbar " id="autocomplete">
<input name="q" type="text" placeholder="Search articles" class="search_input">
<i class="fas fa-search"></i>
<ul class="autocomplete-result-list"></ul>
</div>
</form>
{% endif %}</div>
</div>
{% endblock search %}
{% block content %}
<div class="d-flex justify-content-start pb-4">Search results for my question: <div class="ml-1 fw-bold"> {{ query_name }} </div></div>
<div class="container-fluid pb-4">
<h4>Articles</h4>
<hr>
<div class="row row-flex row-cols-1 row-cols-md-3 g-4">
{% for article in search_articles %}
<div class="col-lg-3 d-flex align-items-stretch">
<a href="{{ article.get_absolute_url }}">
<div class="card h-100 shadow text-left">
<h5 class="card-header">{{article.title}}</h5>
<img src="/static/preview_homepage3.png" class="card-img-top">
<div class="card-body">
<h5 class="card-title">{{ article.slug }}</h5>
<p class="card-text">
{% comment %} {% lorem 10 w %} {% endcomment %}
{{article.body | safe | truncatechars:75}}
</p>
</a><br>
{% include 'main/tag_cards.html' %}
</div>
<div class="card-footer">
<small class="text-muted">{{ article.publish|date:"d F Y" }}</small>
</div>
</div>
</div>
{% empty %}
<div class="container d-flex justify-content-center">No results</div>
{% endfor %}
</div>
</div>
<h4>Related questions</h4>
<hr>
<div class="container h-100 py-2 mb-4">
{% for qa in qa_list %}
<div class="card text-dark bg-light mb-3 text-left">
<a href="{{ qa.get_absolute_url }}">
<h5 class="card-header">Q: {{qa.title}}</h5>
<div class="card-body">
<div class="card-title text-justify">A: {{ qa.answer |safe | striptags }}</div>
{% comment %} <p class="card-text"> {{ qa.author }}</p> {% endcomment %}
</div>
<div class="card-footer">
<small class="text-muted">Published: {{qa.publish}}</small>
</div>
</a>
</div>
{% empty %}
<p>No results</p>
{% endfor %}
{% endblock %}
You can make use of Django's distinct() QuerySet method
.disctinct() Returns a new QuerySet that uses SELECT DISTINCT in its SQL query. This eliminates duplicate rows from the query results.
Change
article = Article.objects.filter(lookups)
to
article = Article.objects.filter(lookups).distinct()
Why does it happen?
In your case, this happens because you are using the Q object,
lookups = Q(title__icontains=query) | Q(tags__name__icontains=query)
suppose your search text is "test" and you have a row in the table with title="text" and tag_name="text", then the lookup will match both title and tag which leads to generating duplicate rows (since you are performing an OR operation in your lookkups) with the same result.
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
{% for post in posts %}
<div class="post-preview">
<a href="{{ url_for('post', post_id=post.id) }}">
<h2 class="post-title">
{{ post.title }}
</h2>
<h3 class="post-subtitle">
{{ post.subtitle }}
</h3>
</a>
<p class="post-meta">Posted by {{ post.author }} on {{ post.date_posted.strftime('%B %d, %Y') }}</p>
</div>
{% if post == posts[-1] %}
<br />
{% else %}
<hr />
{% endif %}
{% endfor %}
Im making a web application on flask and this is the snippet of my code to the articles template I have a sqlite database that contains the articles, how can I make an if statement that detects if the post is the last in the loop since im making an hr per article but not on the last one
{% if post == posts[-1] %} doesn't seem to work.
By Default Flask uses jinja2 as default Template Engine[1] and that's what you're using. Jinja2 provides loop.last variable[2] that you can use as follows:
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
{% for post in posts %}
<div class="post-preview">
<a href="{{ url_for('post', post_id=post.id) }}">
<h2 class="post-title">
{{ post.title }}
</h2>
<h3 class="post-subtitle">
{{ post.subtitle }}
</h3>
</a>
<p class="post-meta">Posted by {{ post.author }} on {{ post.date_posted.strftime('%B %d, %Y') }}</p>
</div>
{% if loop.last %}
<br />
{% else %}
<hr />
{% endif %}
{% endfor %}
I'm new to Django so apologies if this one is silly. I have a Django template with three spots for images, and I'm trying to let an admin user choose which image in the database should go in which spot (left, middle or right). However,
My model looks like this:
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
class Artwork(models.Model):
art = models.ImageField(upload_to='artworks/%Y')
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
date = models.DateField(auto_now_add=True)
herochoices = [('left', 'left'), ('middle', 'middle'), ('right', 'right')]
hero = models.CharField(choices=herochoices, max_length=6, unique=True, null=True, blank=True, error_messages={'unique':'Another artwork already uses this hero position.'})
slug = slugify(title, allow_unicode=False)
def get_absolute_urls(self):
return reverse('artwork_list', kwargs={'slug': self.slug})
And my template looks like this:
{% extends 'base.html' %}
{% block content %}
<div class="container">
<div class="row">
{% for artwork in object_list %}
{% if artwork.hero == 'left' %}
<div class="col-sm p-3 align-items-center">
<img class="img-fluid rounded" src="{{ artwork.art.url }}" />
<p>{{ artwork.hero }}</p> <!--for testing-->
</div>
{% elif artwork.hero == 'middle' %}
<div class="col-sm p-3 align-items-center">
<img class="img-fluid rounded" src="{{ artwork.art.url }}" />
<p>{{ artwork.hero }}</p> <!--for testing-->
</div>
{% elif artwork.hero == 'right' %}
<div class="col-sm p-3 align-items-center">
<img class="img-fluid rounded" src="{{ artwork.art.url }}" />
<p>{{ artwork.hero }}</p> <!--for testing-->
</div>
{% endif %}
{% endfor %}
</div>
</div>
{% endblock content %}
For some reason the images are displayed in the wrong order:
I have been looking at this for forever, any help is much appreciated!
The template you are generating with Django is not the following, since the for loop does simply follow the queryset items order.
<div class="container">
<div class="row">
<div class="col-sm p-3 align-items-center">
<img class="img-fluid rounded" src="{{ LEFT URL }}" />
<p>{{ LEFT HERO }}</p>
</div>
<div class="col-sm p-3 align-items-center">
<img class="img-fluid rounded" src="{{ MIDDLE URL }}" />
<p>{{ MIDDLE HERO }}</p>
</div>
<div class="col-sm p-3 align-items-center">
<img class="img-fluid rounded" src="{{ RIGHT URL }}" />
<p>{{ RIGHT URL }}</p>
</div>
</div>
</div>
In this snippet, three images will be ordered. If you have more than three, you should make the queryset "smarter" (i.e. a simple get won't work).
URL:
def example(request):
qs = Artwork.objects.all()
objects_list = [qs.get(hero=position) for position in ["left", "middle", "right"]]
return render("test.html", { "objects_list": objects_list})
HTML:
{% extends 'base.html' %}
{% block content %}
<div class="container">
<div class="row">
{% for artwork in object_list %}
<div class="col-sm p-3 align-items-center">
<img class="img-fluid rounded" src="{{ artwork.art.url }}" />
<p>{{ artwork.hero }}</p>
<!--for testing-->
</div>
{% endfor %}
</div>
</div>
{% endblock content %}
so i have an issue where everything works as it should in chrome but in safari some things are just not displayed as if they weren't there.
in my nav it should have products, about, contact and blog in chrome it displays as such, but in safari the contact link is missing. when i checked the inspector its not even hidden its just not in the code.
and one of my filters on the product page again works fine in chrome but in safari the indiviudals tab just doesn't display any content and the medical schools tab is missing one of its items.
product page
<section class="resource-list-block content-block">
<div class="product-overview col-sm-offset-1 col-sm-10 col-xl-offset-1 col-xl-10 resource-list-block__list">
{% for product_page in product_pages %}
{% if product_page.get_content_model.public %}
<div class="col-sm-6 col-md-4 col-xl-4 cover resource-list-block__list__item resource-list-block__list__item--important filterable product-list-block__list__item filtered-cat filtered-filt" data-category="{{ product_page.get_content_model.specialties.all|specialties }}" data-filter="{{ product_page.get_content_model.tags.all|tags }}">
<a href="{{product_page.get_absolute_url}}">
{% include "includes/product-cover.html" with product=product_page.get_content_model.product %}
</a>
</div>
{% endif %}
{% endfor %}
</div>
product-item section
{% load staticfiles compress %}<div class="sans-serif cover-page">
<figure class="figure-cover" style="background-color:#{{product.theme_color}} !important;">
<div class="cover-img center-block"><img src="{{product.element_icon.url}}" class="img-responsive center-block" alt="{{product.title}} Image"></div>
<div class="product-count">
<div class="text-center"><i class="fa fa-calendar"></i><span class="small-text"> {{ product.updates_per_year }} updates per year</span></div>
</div>
<div class="clearfix"></div>
<div class="text-center type-name">
<h3 class="sans-serif">{{ product_page.get_content_model.product_type | upper }}</h3>
<h4 class="sans-serif hidden-md hidden-sm hidden-xs">{{ product_page.get_content_model.editor_text }} <br> {{ product_page.get_content_model.editor_title_text }}</h4>
<h4 class="sans-serif">ISSN {{ product.issn }}</h4>
</div>
</figure>
<figure class="product-content" {% if product.theme_color = 'AF1F24' %} style="background-color:#f2e4e5 !important" {% endif%}>
<div class="cover-img center-block"><img src="{{product.element_icon_alt.url}}" class="img-responsive center-block" alt="{{product.title}} Image"></div>
<div class="clearfix"></div>
<h2 class="text-center type-name">{{ product.title | upper }}</h2>
<figcaption>
<p>{{ product_page.get_content_model.intro }}</p>
</figcaption>
</figure>
and the nav code
{% load pages_tags i18n future %}{% spaceless %}<ul class="decker-menu generic-nav-list generic-nav-list--horizontal theme" id="hero-nav">
{% for child_page in page_branch %}
{% if child_page.in_menu %}
<li class="decker-menu__item">
<a {% if child_page == page or child_page in page.get_ascendants %} class="active important" {% endif %} href="{% if child_page.slug|slice:":4" == 'http' %}{{ child_page.slug }}{% else %} {{ child_page.get_absolute_url }}{% endif %}" >{{ child_page.title }}</a>
</li>
{% endif %}
{% endfor %}<li class="decker-menu__item login-btn"><a href="#">Menu</li></ul>{% endspaceless %}
had to go into mezzanine on safari then remove the content save and refresh the page then go back and re-add it to fix the issue. then repeated that step to fix the issue in firefox.... so weird
thanks!
I have a django for loop that is supposed to add items inside a form element. However, when the code executes, django just puts the first element inside the form and puts the following element outside the form html tag.
The code is:
<form action="." method="post" class="basket_summary" id="basket_formset">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{% with line=form.instance product=form.instance.product %}
{% purchase_info_for_line request line as session %}
<div class="row no-margin cart-item">
{{ form.id }}
<div class="col-xs-12 col-sm-2 no-margin">
{% with image=product.primary_image %}
{% thumbnail image.original "100x100" upscale=True as thumb %}
<a href="{{ product.get_absolute_url }}" class="thumb-holder">
<img class="lazy" alt="" src="{{ thumb.url }}" />
</a>
{% endthumbnail %}
{% endwith %}
</div> <!-- /.thumbnail holder -->
<div class="col-xs-12 col-sm-5 ">
<div class="title">
{{ line.description }}
</div>
{% trans "Update" %}
{% if user.is_authenticated %}
| {% trans "Save for later" %}
{% endif %}
<div style="display:none">
{{ form.save_for_later }}
{{ form.DELETE }}
</div>
{% for field_errors in form.errors.values %}
{% for error in field_errors %}
<span class="error-block"><i class="icon-exclamation-sign"></i> {{ error }}</span>
{% endfor %}
{% endfor %}
</div> <!-- /.Title holder -->
<div class="col-xs-12 col-sm-3 no-margin">
<div class="quantity">
<div class="le-quantity">
<form>
<a class="minus" href="#reduce"></a>
<input name="form-0-quantity" id="id_form-0-quantity" readonly="readonly" type="text" value="{{ form.quantity.value }}" />
<a class="plus" href="#add"></a>
</form>
</div>
</div>
</div><!-- /.Quantity Holder -->
<div class="col-xs-12 col-sm-2 no-margin">
<div class="price">
{% if line.is_tax_known %}
{{ line.unit_price_incl_tax|currency:line.price_currency }}
{% else %}
{{ line.unit_price_excl_tax|currency:line.price_currency }}
{% endif %}
</div>
</div> <!-- /.Price Holder -->
</div><!-- /.cart-item -->
{% endwith %}
{% endfor %}</form>
What I expect is that django should have multiple <div class="row no-margin cart-item"> items in the form tag but that isn't happening.
How do I fix this?
Looks like you are missing closing form tag </form> at the end.
EDIT: as others mentioned in comments it could be because you have forms inside form. This will result in unpredictable behavior.