How to add html inside {{ }} in django template - python

I want to know how to add html inside {{ }}:
{{ article.tags.all|join:", " }}
This return tags separated by coma for example: sports, cricket, nature etc
I want to do this:
{{ <span class="label">article.tags.all|join:", "</span> }}
I want to design each tag with adding a span class and remove coma
Models.py:
class Tag(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=255, null=True, default='')
class article(models.Model):
title = models.CharField(max_length=250)
disc = models.TextField(verbose_name="Discription")
posted = models.DateTimeField(auto_now_add=True, editable=False)
updated = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)

Try with this:
{% for tag in article.tags.all %}
<span class="label">{{ tag }}</span>{% if not forloop.last %}, {% endif %}
{% endfor %}
After following the discussion:
{% for tag in article.tags.all %}
{% if tag.title == 'hello' %}
Special tag: <span>{{ tag }}</span>
{% else %}
<span>{{ tag }}</span>
{% endif %}
{% endfor %}

Related

Could not parse the remainder:

I saw many questions about this error, but all are distincts and not apply to me, so...
My models.py
# Category
class Category(models.Model):
category_name = models.CharField(max_length=64)
def __str__(self):
return f"{self.category_name}"
# Item
class Item(models.Model):
item_name = models.CharField(max_length=64)
category = models.ForeignKey(Category, on_delete= models.CASCADE, related_name="items_by_category")
price_small = models.DecimalField(help_text="Price in U$S",max_digits=6, decimal_places=2, default= 0)
price_large = models.DecimalField(help_text="Price in U$S",max_digits=6, decimal_places=2, default= 0)
nradd = models.IntegerField(default=0)
def __str__(self):
return f"{self.category} {self.item_name} - Qty.of Adds: {self.nradd} - Price Small: {self.price_small} - Price Large: {self.price_large}"
My views.py
def menu(request):
products = list(Item.objects.all().values().order_by('category'))
categories = list(Category.objects.all().prefetch_related('items_by_category'))
extras = list(Extra.objects.filter(category="T"))
subsextras = list(Extra.objects.filter(category="S"))
context = {
'Products' : products,
'Categories': categories,
'Extras' : extras,
'Subextras' : subsextras
}
return render(request, 'orders/menu.html',context)
First, I'm trying to simply list the categories with the items who belongs to:
My menu.html:
{% extends 'orders/base.html' %}
{% load static %}
{% block title %}
Menu
{% endblock %}
{% block body %}
<ul>
{% for cate in Categories %}
<li>{{ cate.category_name }}</li>
<ul>
{{% for myitem in cate.items_by_category.all %}}
<li>{{ myitem.item_name }}</li>
{{% endfor %}}
</ul>
{% endfor %}
</ul>
{% endblock %}
the error appears in the line:
{{% for myitem in cate.items_by_category.all %}}
Same commands in the shell goes well:
cate = Category.objects.get(category_name="Salads")
cate.items_by_category.all()
Thanks in advance,
It's about Template Language.
Variables look like this: {{ variable }}.
Filters look like this: {{ name|lower }}.
Tags look like this: {% tag %}.
To comment-out part of a line in a template, use the comment syntax:
{# #}
There is no such thing as {{% %}}
So, instead of
{{% for myitem in cate.items_by_category.all %}}
You should use
{% for myitem in cate.items_by_category.all %}
Reference:
https://docs.djangoproject.com/en/3.0/ref/templates/language/
The template tags are sourrounded with {% … %}, not {{% … %}}. So you should rewrite the template to:
{% extends 'orders/base.html' %}
{% load static %}
{% block title %}
Menu
{% endblock %}
{% block body %}
<ul>
{% for cate in Categories %}
<li>{{ cate.category_name }}</li>
<ul>
{% for myitem in cate.items_by_category.all %}
<li>{{ myitem.item_name }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>

display contents of manytomany and foreignjey fields in Django

I'm new to Django and I'ma building a basic blog application.
I cant show manytomany field (in tags) and a foreignkey field (comments) in my details page.
models.py
class BlogContent(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
content = models.TextField()
date_published = models.DateField(auto_now=True)
image = models.ImageField(upload_to='media/')
def __str__(self):
return self.title
class TagName(models.Model):
tag = models.ManyToManyField(BlogContent, null=True)
name = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.name
class Comment(models.Model):
comt_text = models.TextField()
comments = models.ForeignKey(BlogContent, on_delete=models.CASCADE)
date_published = models.DateField(auto_now=True)
name = models.CharField(max_length=200, blank=True, null=True)
def __str__(self):
return self.name
views.py
def details(request, blogcontent_id):
data_blog = get_object_or_404(BlogContent, pk=blogcontent_id)
data_tag = get_object_or_404(TagName, pk=blogcontent_id)
data_comment = Comment.objects.select_related()
return render(request, 'details.html',
{'data_blog': data_blog, 'data_tag':data_tag, 'data_comment':data_comment})
details.html
{% extends 'base.html' %}
{% block body_base %}
<img class="card-img-top img-responsive" src={{ data_blog.image.url }} alt="Card image cap">
<h2 class="blog-post-title">{{ data_blog.title }}</h2>
<p class="blog-post-meta">{{ data_blog.date_published }} {{ data_blog.author }}</p>
<p>{{ data_blog.content }}</p>
{% endblock %}
how do i show foreignkey and manaytomany fieds after this?
TBH this is much easier if you use class based views.
The view would simply be:
class BlogContentDetail (DetailView):
model = BlogContent
The url call would be url(r'^blog-detail/(?P<pk>\d+)/$, BlogContentDetail.as_view(), name="blog_detail")
Your html file should be called blogcontent_detail.html and held within the app subfolder in the templates folder
The template would then be:
{% extends 'base.html' %}
{% block body_base %}
<img class="card-img-top img-responsive" src={{ object.image.url }} alt="Card image cap">
<h2 class="blog-post-title">{{ object.title }}</h2>
<p class="blog-post-meta">{{ object.date_published }} {{ object.author }}</p>
<p>{{ object.content }}</p>
{% for tag in object.tags_set.all %}{{ tag }}{% endfor %}
{% endblock %}
You can iterate the ManyToMany Field in this way
{% for tags in data_tag.tag.all %}
<p > {{tags}} </ p>
{% endfor %}
For foreign key
{{data_comment.comments}}

Django - Sum of different Currencies

we are currently building a cryptocurrency market (university project)
Each user has different cryptocurrencies in his "Wallet"
The wallet should show the sum (+ and - transactions) for each of the different cryptocurrencies.
For the moment we are only able to render a list which doesn't group the different currencies (those who have the same name)
We tried the sum and annotate functions. By doing so we aren't able to display the currency name. We get only the currency id
Here is our models file
class Currency(models.Model):
currency_name = models.CharField(max_length=40, unique=True)
symbol = models.ImageField(blank=True)
ticker = models.CharField(max_length=10)
created_at = models.DateTimeField(auto_now_add = True, null=True)
class Transaction(models.Model):
listing_id = models.ForeignKey(Listing, on_delete=models.CASCADE, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add = True)
exchange_amount = models.IntegerField(null=True)
user_debit = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_id_debit', null=True)
user_credit = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_id_credit', null=True)
currency_id = models.ForeignKey(Currency, on_delete=models.CASCADE, null=True)
And our views.py
#profile page
#login_required
def profile(request):
wallet = Transaction.objects.filter(Q(user_credit=request.user) | Q(user_debit=request.user)).order_by('-created_at')
transactions = Transaction.objects.filter(Q(user_credit=request.user) | Q(user_debit=request.user)).order_by('-created_at')[:10]
listings = Listing.objects.filter(user=request.user).order_by('-created_at')[:10]
args = {'wallets': wallet, 'transactions': transactions, 'listings': listings}
return render(request, 'profile.html', args)
<!--This is our custom head title for the different urls. The base.html is loaded after this.-->
<head>
<title>SolvayCoin - Profile</title>
</head>
{% extends 'base.html' %}
{% block content %}
{% if user.is_authenticated %}
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
<h1 class="display-4">{{ user.first_name }} {{ user.last_name }}'s profile</h1>
<p>Username is <pan style="font-style: italic">{{ user.username }}</pan> and joined SolvayCoin {{ user.date_joined|timesince }} ago</p>
</div>
</div>
<div class="container extra-padding">
<hr>
<div class="row">
<div class="col-md-4">
<h2>My wallet</h2>
<ul class=list-unstyled >
{% for wallet in wallets %}
<li>{{ wallet.currency_id }}: {{ wallet.exchange_amount__sum|floatformat:"2" }}</li>
{% endfor %}
</ul>
</div>
<div class="col-md-4">
<h2>My transactions</h2>
{% if transactions %}
<ul class=list-unstyled >
{% for transactions in transactions %}
<li>
{% if user == transactions.user_credit %}
(+)
{% elif user == transactions.user_debit %}
(-)
{% endif %}
{{ transactions.currency_name_fixed }}{{ transactions.exchange_amount|floatformat:"2" }}
with {% if user == transactions.user_credit %}{{ transactions.user_debit }}{% elif user == transactions.user_debit %}{{ transactions.user_credit }}{% endif%}
</li>
{% endfor %}
</ul>
{% else %}
<p>No transactions are available.</p>
{% endif %}
</div>
<div class="col-md-4">
<h2>My listings</h2>
{% if listings %}
<ul class=list-unstyled >
{% for listings in listings %}
<li>Listing <!--{{ listings.id }}--> created {{ listings.created_at|date:'d/m/Y' }} at {{ listings.created_at|date:'H:i' }}</li>
{% endfor %}
</ul>
{% else %}
<p>No listings are available.</p>
{% endif %}
</div>
</div>
{% endif %}
<hr>
</div> <!-- /container -->
{% endblock %}
A django queryset solution seems tricky; since debit/credit resolution is also required here.
If performance and doing it in DB are not a major concern; I would do it in python as follows:
wallet_transactions = Transaction.objects.filter(Q(user_credit=request.user) | Q(user_debit=request.user)).order_by('-created_at').select_related('currency_id')
wallet = get_wallet(request.user, wallet_transactions)
def get_wallet(user, wallet_transactions):
wallet = defaultdict(int)
for txn in wallet_transactions:
if user == txn.user_credit:
wallet[txn.crrency_id.currency_name] += txn.exchange_amount
elif user == txn.user_debit:
wallet[txn.crrency_id.currency_name] -= txn.exchange_amount
else:
# Error; invalid transaction
pass
return wallet
# This will return something like this: {'SBS': 300, 'BTC': 121000}
I'd also think that there will be more business logic that gets added to get_wallet which definitely makes sense to be kept in the business layer of your application (python).
In your html; you can iterate over the wallet contents and print as follows:
<ul>
{% for currency_name, amount in wallet.items %}
<li>{{currency_name}} - {{amount}}</li>
{% endfor %}
</ul>
In your specific case; change this snippet:
<ul class=list-unstyled >
{% for currency_name, amount in wallet.items %}
<li>{{ currency_name }}: {{ amount|floatformat:"2" }}</li>
{% endfor %}
</ul>

How to sort based on a choice field in django in template

Consider the following model:
class Category(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
POSITIONS = (
('L', 'Left'),
('R', 'Right')
)
position = models.CharField(max_length=1, choices=POSITIONS, default='R')
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
I want to sort the objects in a manner such that I can separate the left ones from the right ones and show them in separate parts of the html document. Something like:
{% for category in categories|sort_by: "position" = "left" %}
<ul class="collection with-header">
<li class="collection-header">
<h3>{{category.name}}</h3>
<p><small>{{category.description}}</small></p>
</li>
{% for url in category.extra_link_set.all %}
<li class="collection-item">{{url.url_text}}</li>
{% endfor %}
</ul>
{% endfor %}
I know this wont work. But I am just trying to give an idea as to what I want. Also would the process be similar for any other field type in django models?
You could try something like this:
{% for category in categories %}
<div class="left_stuff">
{% if category.position=='L' %}
<h3>...</h3>
.....
{% endif %}
</div>
{% endfor %}
{% for category in categories %}
<div class="right_stuff">
{% if category.position=='R' %}
<h3>...</h3>
.....
{% endif %}
</div>
{% endfor %}

How to connect model with the model via Foreign Key in template

I have a gallery (app in django 1.8), to which they are plugged in images. My problem is that create a link to the images in each category. I do not know how to do it on the side of the template and URL addresses are correct.
Models
class Gallery(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
image = ThumbnailerImageField(upload_to='paint/%Y/%m/%d')
class Meta:
verbose_name = "Gallery"
verbose_name_plural = " Galleries"
def __unicode__(self):
return self.title
class Paint(models.Model):
AVAILABLE = "Available"
NOT_AVAILABLE = "Not available"
STATUS_PAINT = (
(AVAILABLE, u"Dostępny"),
(NOT_AVAILABLE, u"Nie dostępny")
)
title = models.CharField(max_length=200)
gallery = models.ForeignKey(Gallery)
paint = ThumbnailerImageField(upload_to='paint/%Y/%m/%d')
price = models.CharField(max_length=50, blank=True, null=True)
status = models.CharField(choices=STATUS_PAINT, default=AVAILABLE, max_length=50)
class Meta:
verbose_name = "Picture"
verbose_name_plural = "Images"
def __unicode__(self):
return self.title
Views
class GalleryView(generic.ListView):
model = Paint
template_name = "www/gallery_list.html"
context_object_name = "gallery"
def get_queryset(self):
return Paint.objects.all()
class GalleryDetailsView(generic.ListView):
model = Gallery
context_object_name = "images"
template_name = "www/gallery_details.html"
urls
urlpatterns = [
url(r'^$', MainPage.as_view(), name='mainpage'),
url(r'^about/$', AboutMe.as_view(), name="about"),
url(r'^gallery/$', GalleryView.as_view(), name="gallery"),
url(r'^gallery1/$', GalleryDetailsView.as_view(), name="gallery_details"),
url(r'^contact/$', contact, name="contact"),
]
Template gallery list - main section
{% extends "base.html" %}
{% load thumbnail %}
{% block content %}
{% for i in images %}
<div class="row">
<div class="col-md-5">
<img src="{{ i.image|thumbnail_url:'avatar1' }}"/>
</div>
<div class="col-md-7">
<h3>{{ i.title }}</h3>
<p>{{ i.description }}</p>
</div>
</div>
<hr>
{% endfor %}
{% endblock %}
{% block content_bottom %}{% endblock content_bottom %}
Template gallery details with images of gallery
{% extends "base.html" %}
{% load thumbnail %}
{% block content %}
<table class="center-table">
<tbody>
{% for image in gallery %}
{% if forloop.counter0|divisibleby:3 %}<tr>{% endif %}
<td style="padding-left:50px;padding-right:50px;color:grey">
<a data-lightbox="roadtrip" href="{{ image.paint.url }}"><img src="{{ image.paint|thumbnail_url:'avatar' }}" class="img-thumbnail img-responsive" /></a><br>
<div style="padding-top:8px;padding-bottom:20px;">
<b>Tytuł:</b> {{ image.title }}<br>
<b>Status: </b>{{ image.status }}<br>
<b>Cena: </b>{{ image.price }}<br>
</div>
</td>
{% if forloop.counter|divisibleby:3 or forloop.last %}</tr>{% endif %}
{% endfor %}
</tbody>
</table>
{% endblock %}
{% block content_bottom %}{% endblock content_bottom %}

Categories

Resources