i have 2 tables in DB wallet(id,name) and balance(id,wallet_id)
i need table consisting of 2 cells (post,date)
where will all wallets in first cell and them balance in second
{% for wallets1 in wallets %}
<tr>
{% for balance1 in balance %}
{% if balance1.wallet_id == wallets1.id %}
<td> {{ balance1.balance }}</td>
{% endif %} {% endfor %}
{% endfor %}
if we have balance of coin we print balance
if balance1.wallet_id need print "0"
The difficulty next. If i do that
{% for wallets1 in wallets %}
<tr>
{% for balance1 in balance %}
{% if balance1.wallet_id == wallets1.id %}
<td> {{ balance1.balance }}</td>
{% else %}
<td> 0</td>
{% endif %} {% endfor %}
{% endfor %}
zero will be printed many times
views
wallets = Wallet.objects.all()
balance = User_balance.objects.filter(user_id= user.id)
args['wallets'] = wallets
args['balance'] = balance
return render_to_response("coins.html", args, user.id)
model
class Wallet(models.Model):
name = models.CharField(max_length=100)
class User_balance(models.Model):
user_id = models.IntegerField()
wallet_id = models.IntegerField()
balance = models.CharField(max_length=100)
You didn't post your view nor models so we have to assume a couple things but basically you're doing it wrong. Since balances have a foreign key on wallets, you don't have to loop over all balances for each wallets, you can just use the reverse relationship:
{% for wallet in wallets %}
<tr>
{% for balance in wallet.balance_set.all %}
<td> {{ balance.balance }}</td>
{% else %}
<td> 0</td>
{% endfor %}
</tr>
{% endfor %}
you must annotate balance in your view like this
wallers = Wallet.objects.all().annotate(total_balance=models.Count('balance'))
...
return render(request, 'template.html', {"wallets": wallets})
then in your html print wallets like this
<table>
<tr><th>wallet</th><th>balance</th></tr>
{% for wallet in wallets %}
<tr>
<td>{{ wallet.name }}</td>
<td>{{ wallet.total_balance|default:0 }}</td>
</tr>
{% endfor %}
</table>
Related
if my table is like this
how can I output the number of events with the same name, like test should be 5 and hello should be 3.
Edit:
Here's my Jinja2 code snippet
{% for event in events %}
{% set count = 0 %}
<tr>
<td>{{ event.name }}</td>
{% for ticket in tickets %}
{% if ticket.event_name == event.name%}
{% set count = count + 1 %}
{% endif %}
{% endfor %}
<td>{{count}}<td>
<td>
But its not counting right
Never mind, I was able to solve it.
{% for event in events %}
{% set count = namespace(value=0) %}
<tr>
<td>{{ event.name }}</td>
{% for ticket in tickets %}
{% if ticket.event_name == event.name%}
{% set count.value = count.value + 1 %}
{% endif %}
{% endfor %}
<td>{{count.value}}<td>
<td>
i am working on hotel booking app , in this i want to display the image of a hotel, based on user entered location . In this if i am displaying all hotels , i am able to display an image , if i am trying to displaying an image through some CRUD operations, i am unable to display it. Here are my code snippets.
class Customer_details(models.Model):
Name = models.CharField(max_length=128)
Age = models.IntegerField()
Mobile_number = models.IntegerField()
Email = models.EmailField()
Address = models.CharField(max_length=50)
Special_request = models.CharField(max_length=50, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.Name
hotel_rating_choices = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('5','5'),
('6','6'),
('7','7'),
)
class Hotel(models.Model):
Hotel_Name = models.CharField(max_length=50)
location = models.CharField(max_length=20)
no_of_rooms = models.IntegerField()
rating = models.CharField(max_length=1, choices=hotel_rating_choices, default=3)
hotel_img = models.ImageField(upload_to='hotel_images/')
uploaded_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.Hotel_Name
class Hotel_image(models.Model):
hotel_img = models.ImageField(upload_to = 'hotel_images/')
hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE)
def __str__(self):
return self.hotel
Ignore the remaining models just concentrate on Hotel model .
`Below code snippet is my view regarding to query.
def get_hotels_by_location(request):
location = request.POST.get('location')
print(location)
location = location.lower()
result = Hotel.objects.values('Hotel_Name', 'rating', 'hotel_img').filter(location=location)
context = {'hotels': result, 'header': ['Hotel_Name', 'Rating', 'image'] }
return render(
request,
template_name='display_hotel_by_location.html',
context=context
)
And below is my django html template
<table class="table">
<tr>
{% for i in header %}
<th>
{{ i }}
</th>
{% endfor %}
</tr>
{% for element in hotels %}
<tr>
{% with i=0 %}
{% for key, value in element.items %}
{% if i == 2 %}
<td> <img src="{{ element.url }}" width = "300" height="300"> </td>
{% endif %}
<td> {{ value }} </td>
{% with j=i %}
j=j+1
i=j
{% endwith %}
{% endfor %}
</tr>
{% endfor %}
</table>
Please help me on this issue.
Change your Hotel_image class to add related name at your foreign to use it further
class Hotel_image(models.Model):
hotel_img = models.ImageField(upload_to = 'hotel_images/')
hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name="hotel_images")
Clean up a bit your views, you dont really need use values in that case.
from .models import Hotel
def get_hotels_by_location(request):
location = request.POST.get('location').lower()
result = Hotel.objects.filter(location=location)
context = {'hotels': result, 'header': ['Hotel_Name', 'Rating', 'image'] }
return render(
request,
template_name='display_hotel_by_location.html',
context=context
)
HTML 1 - If you consuming the hotel_img from class Hotel use this one
<table class="table">
<tr>
{% for i in header %}
<th>{{ i }}</th>
{% endfor %}
</tr>
{% for hotel in hotels %}
<tr>
{% if forloop.counter0 == 2 and hotel.hotel_img %}
<td> <img src="{{ hotel.hotel_img.url }}" width="300" height="300"> </td>
{% endif %}
<td> {{ hotel.Hotel_Name }} </td>
</tr>
{% endfor %}
</table>
HTML 2 - If you using the class Hotel_image use like that
<table class="table">
<tr>
{% for i in header %}
<th>{{ i }}</th>
{% endfor %}
</tr>
{% for hotel in hotels %}
<tr>
{% for img in hotel.hotel_images %}
{% if img.hotel_img %}
<td> <img src="{{ img.hotel_img.url }}" width="300" height="300"> </td>
{% endif %}
{% endfor %}
<td> {{ hotel.Hotel_Name }} </td>
</tr>
{% endfor %}
</table>
More info about Django relations: https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ForeignKey.related_name
You can use Template Tags too to filter all images from your Hotel_Image
1 - Create one folder called templatetag and inside that one file inside it to be your templatetag inside your app folder
hotel/templatetags/hotel_templatetag.py
Inside the file put that code
from django import template
from .models import Hotel_image
register = template.Library()
def get_hotel_images(self):
return Hotel_image.objects.filter(id=self.id)
You Html should be like that
<table class="table">
<tr>
{% for i in header %}
<th>{{ i }}</th>
{% endfor %}
</tr>
{% for hotel in hotels %}
<tr>
{% for img in hotel|get_hotel_images %}
{% if img.hotel_img %}
<td> <img src="{{ img.hotel_img.url }}" width="300" height="300"> </td>
{% endif %}
{% endfor %}
<td> {{ hotel.Hotel_Name }} </td>
</tr>
{% endfor %}
</table>
More info about templatetags: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/
I'm pretty new to django so I apologize if this has an obvious answer.
Say you have the following three models:
models.py
class Customer(models.Model):
name = models.CharField()
slug = models.SlugField()
class Product(models.Model):
plu = models.Charfield()
description = models.Charfield()
class Template(models.Model):
customer = models.ForeignKey(Customer)
product = models.ForeignKey(Product)
price = models.DecimalField()
The inline formset would look something like:
TemplateFormSet = inlineformset_factory(Customer, Template, extra=0,
fk_name='customer', fields=('price'))
Is it possible to follow the Template formset's Product foreign key backwards so you could display the plu and description fields within the same table?
For example something like this:
<table>
<tbody>
{% for obj in customer.template_set.all %}
<tr>
<td>{{ obj.product.plu }}</td>
<td>{{ obj.product.description }}</td>
<td>{% render_field formset.form.price class="form-control form-control-sm" %}</td>
</tr>
{% endfor %}
</tbody>
</table>
The formset's fields appear with the html above but the data from the bound form instance doesn't appear and I can't save by editing the empty fields.
I've also tried below but each formset is repeated for each object (for x formsets there are x*x rows):
<tbody>
{% for obj in customer.template_set.all %}
{% for form in formset %}
<tr>
<td>{{ obj.product.plu }}</td>
<td>{{ obj.product.description }}</td>
<td>{% render_field form.price class="form-control" %}</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
Basically I'm trying to go from the top portion of the image to the bottom
The formset functionality is only to show forms but something that you can do is create a custom form that display the 2 fields with the function of readonly like:
class your_form(models.ModelForm):
class Meta()
model = Template
fields = ['price', 'product']
def __init__(self, *args, **kwargs):
super(ItemForm, self).__init__(*args, **kwargs)
self.fields['product'].widget.attrs['readonly'] = True
TemplateFormSet = inlineformset_factory(Customer, Template, extra=0,
fk_name='customer', form=your_form)
That's my best tried, if you wanna display both try returning in your models something like:
class Product(models.Model):
plu = models.Charfield()
description = models.Charfield()
def __str__(self, *args, **kwargs):
a = '<td>' + self.plu + '</td><td>' + self.plu '</td>'
return self.plu + self.description # Or return 'a'
I managed to get it working although I'm not sure its the most efficient way. If anyone has a better way please let me know.
{{ formset.management_form }}
<table>
<thead>
...
</thead>
<body>
{% for obj in customer.template_set.all %}
{% with forloop.counter as outer_counter %}
{% for form in formset %}
{% if forloop.revcounter == outer_counter %}
{% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %}
<tr>
<td>{{ obj.product.plu }}</td>
<td>{{ obj.product.description }}</td>
<td>{% render_field form.price class="form-control" %}</td>
</tr>
{% endif %}
{% endfor %}
{% endwith %}
{% endfor %}
</tbody>
</table>
Should also mention I'm using django-widget-tweaks which is where {% render_field %} comes from.
Update (the proper way):
{% for template in customer.template_set.all %}
{% for form in formset %}
{% if form.instance.id == template.pk %}
I have a ModelFormSet:
TransactionFormSet = modelformset_factory(Transaction, exclude=("",))
With this model:
class Transaction(models.Model):
account = models.ForeignKey(Account)
date = models.DateField()
payee = models.CharField(max_length = 100)
categories = models.ManyToManyField(Category)
comment = models.CharField(max_length = 1000)
outflow = models.DecimalField(max_digits=10, decimal_places=3)
inflow = models.DecimalField(max_digits=10, decimal_places=3)
cleared = models.BooleanField()
And this is the template:
{% for transaction in transactions %}
<ul>
{% for field in transaction %}
{% ifnotequal field.label 'Id' %}
{% ifnotequal field.value None %}
{% ifequal field.label 'Categories' %}
// what do i do here?
{% endifequal %}
<li>{{ field.label}}: {{ field.value }}</li>
{% endifnotequal %}
{% endifnotequal %}
{% endfor %}
</ul>
{% endfor %}
The view:
def transactions_on_account_view(request, account_id):
if request.method == "GET":
transactions = TransactionFormSet(queryset=Transaction.objects.for_account(account_id))
context = {"transactions":transactions}
return render(request, "transactions/transactions_for_account.html", context)
I want to list all the Transaction information on a page.
How can I list the "account" property of Transaction and the "categories"?
Currently the template shows only their id, I want to get a nice representation for the user (preferrably from their str() method).
The only way I can see that would work is to iterate over the FormSet, get the Ids of the Account and Category objects, get the objects by their Id and store the information I want in a list and then pull it from there in the template, but that seems rather horrible to me.
Is there a nicer way to do this?
Thanks to the comments, I figured it out that what I was doing was pretty dumb and pointless.
This works:
1) Get all Transaction objects
transactions = Transaction.objects.for_account(account_id)
2) Pass to template
context = {"transactions":transactions,}
return render(request, "transactions/transactions_for_account.html", context)
3) Access attributes, done
{% for transaction in transactions %}
<tr>
<td class="tg-6k2t">{{ transaction.account }}</td>
<td class="tg-6k2t">{{ transaction.categories }}</td>
<td class="tg-6k2t">{{ transaction.date }}</td>
<td class="tg-6k2t">{{ transaction.payee }}</td>
<td class="tg-6k2t">{{ transaction.comment }}</td>
<td class="tg-6k2t">{{ transaction.outflow }}</td>
<td class="tg-6k2t">{{ transaction.inflow }}</td>
<td class="tg-6k2t">{{ transaction.cleared }}</td>
</tr>
{% endfor %}
I have the following template in django, i want to get the totals of the last 2 columns for each of my document objects
{% for documento in documentos %}
{% for cuenta in documento.cuentasxdocumento_set.all %}
<tr {% cycle 'class="gray"' '' %} >
{% if forloop.first %}
<td>{{ documento.fecha_creacion.date }}</td>
<td>{{ cuenta.cuenta.nombre }}</td>
<td>
{% if cuenta.monto >= 0 %}
{{ cuenta.monto}}
{% endif %}
</td>
<td>
{% if cuenta.monto <= 0 %}
{{ cuenta.monto }}
{% endif %}
</td>
{% else %}
<td colspan="4"></td>
<td>{{ cuenta.cuenta.codigo }}</td>
<td>{{ cuenta.cuenta.nombre }}</td>
<td>
{% if cuenta.monto <= 0 %}
{{ cuenta.monto }}
{% endif %}
</td>
<td>
{% if cuenta.monto >= 0 %}
{{ cuenta.monto }}
{% endif %}
</td>
{% endif %}
</tr>
{% endfor %}
<tr>
<td colspan="1"></td>
<td>Document Total</td>
<td></td>
<td></td>
</tr>
{% endfor %}
This is all done using the following models, which are simplified for the purpose of this question
class Documento(models.Model):
numero_impreso = models.CharField(max_length=50)
fecha_creacion = models.DateTimeField(auto_now_add = True)
cuentas = models.ManyToManyField('CuentaContable', through = 'CuentasXDocumento', null = True)
def __unicode__(self):
return self.tipo.nombre + ": " + self.numero_impreso
class CuentasXDocumento(models.Model):
cuenta = models.ForeignKey('CuentaContable')
documento = models.ForeignKey('Documento')
monto = models.DecimalField(max_digits= 14, decimal_places = 6)
linea = models.IntegerField()
class CuentaContable(models.Model):
codigo = models.CharField(max_length=50)
nombre = models.CharField(max_length=100)
def __unicode__(self):
return self.nombre
Finally I'm sorry for the bad english :)
From my experience with Django, I would say that these things aren't easily done in the template. I try to do my calculations in the view instead of the template.
My recommendation would be to calculate the two sums you need in the view instead of the template.
That beings said, it is possible to do some work in the template using custom filters and tags. Using filters it might look like this:
<td>{% documento.cuentasxdocumento_set.all | sum_monto:"pos" %}</td>
<td>{% documento.cuentasxdocumento_set.all | sum_monto:"neg" %}</td>
Filters take two arguments, the value that you pass to the filter and an argument that you can use to control its behavior. You could use the last argument to tell sum_monto to sum the positive values or the negative values.
This is a quick untested filter implementation off the top of my head:
from django import template
register = template.Library()
#register.filter
def sum_monto(cuentas, op):
if op == "pos":
return sum(c.monto for c in cuentas if c.monto > 0)
else
return sum(c.monto for c in cuentas if c.monto < 0)