its my first time to ask hope I can find solution to my problem. Am trying to display the courses in an html page using objects.all() but it returns nothing and the page remain empty, even though records do exist in the database. I tried the same method for other pages and it worked, idk what am doing wrong here :(
in view.py
def viewCourse(request):
corlist = Course.objects.all()
#print(muffin)
#course.count()
context = {'corlist':corlist}
return render(request, 'LogInApp/ViewCourse.html', context)
in model.py
class Course(models.Model):
COURSES = (
('Data Structure','Data Structure'),
('Computer Network','Computer Network'),
('Web Design','Web Design'),
('Internet of Things','Internet of Things'),
('Artificial Intelligence','Artificial Intelligence'),
('Artificial Intelligence-Tut', 'Artificial Intelligence-Tut'),
)
course_id = models.AutoField(primary_key=True)
course_name = models.CharField(max_length=100, null=True, choices= COURSES)
fk_lecturer_id = models.OneToOneField(Lecturer, on_delete=models.CASCADE) # foreign key
date = models.DateField(max_length=20, null=True)
time = models.TimeField(max_length=20, null=True)
def __str__(self):
return '{} {}'.format(self.course_id, self.course_name)
#property
def lecturerid(self):
return self.fk_lecturer_id.lecturerid
in ViewCourse.html
<table border="1" class="table">
<tr>
<th>Course ID</th>
<th>Course Name</th>
<th>Course Lecturer</th>
<th>Date</th>
<th>Time</th>
<th width="100px"> </th>
</tr>
{% for co in corlist %}
<tr>
<td> {{ co.course_id }} </td>
<td> {{ co.course_name }} </td>
<td> {{ co.fk_lecturer_id }} </td>
<td> {{ co.date }} </td>
<td> {{ co.time }} </td>
</tr>
{% endfor %}
</table>
Related
I would like to show in my template in each cell the name ("nombre") of the client ("cliente") with his payment {{pago.cantidad_pagada}} , the problem is that as I am doing it {{presupuesto.cliente.nombre}}, I show all the names that I have in my table and they are repeated in each of the cells, I imagine that it is due to the use of "for", but I don't know of another way to display the data.
presupuestos.html
<tbody>
{% for pago in pagos %}
<tr>
<td>
{% for presupuesto in presupuestos %}
{{presupuesto.cliente.nombre}}
{% endfor %}
</td>
<td>
{{pago.cantidad_pagada}}
</td>
</tr>
{% endfor%}
</tbody>
pagos/models.py
class Pagos(models.Model):
numero_transaccion=models.IntegerField()
estimate=models.ForeignKey(Presupuestos, on_delete=models.SET_NULL, null=True)
def __str__(self):
return f'{self.numero_transaccion}'
presupuestos/models.py
class Presupuestos(models.Model):
cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True)
def __str__(self):
return f'{self.cliente}'
clientes/models.py
class Clientes(models.Model):
nombre = models.CharField(max_length=200, blank=True)
def __str__(self):
return f'{self.nombre}'
views.py
def presupuestosIndex(request):
presupuestos = Presupuestos.objects.all()
pagos=Pagos.objects.all()
return render(request, "Presupuestos/presupuestos.html", {'presupuestos':presupuestos,'pagos':pagos})
You have a foreign key estimate from Pagos to Presupuestos. If that's the relationship you wish to display for each pago you would do
<tbody>
{% for pago in pagos %}
<tr>
<td>
{{pago.estimate.cliente.nombre}}
</td>
<td>
{{pago.cantidad_pagada}} <! not in the models in the question -->
</td>
</tr>
{% endfor%}
</tbody>
I want to display a table with :
on rows: the date for each weekday (calculate in my views.py)
on columns: the Mealselection of an user.
I can get value from models and display it :
https://i.imgur.com/TyvI0DH.png
But when i look source code on the page i see https://i.imgur.com/wY0QC62l.png
So obviously it does not work when i try to save the user choice because it will update only one date, today for exemple, since there are the same form id i think.
I try with a formset but i can't pass initial value to the template "selection_template.html" (i try with the exemple below but don't work because i need to display the user selection in relation with date of weekday.
formset = ArticleFormSet(initial=[{'title': "Form %d" % (i+1),
'pub_date': datetime.date.today()} for i in range(10)])
I know how to display multi form using formset but don't know how to pass value to the template.
models.py
class MealSelection(models.Model):
user = models.ForeignKey('User', on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
salad = models.BooleanField(default=False)
meal = models.BooleanField(default=False)
sandwich = models.BooleanField(default=False)
forms.py
class GetUserMeal(forms.ModelForm):
class Meta:
model = MealSelection
fields = ['meal', 'salad', 'sandwich']
widget = forms.CheckboxInput(
attrs={
'name': 'choices'
}
)
views.py
for day in weekDay:
try:
userSelection = MealSelection.objects.get(user=u1,date=startWeek + datetime.timedelta(days=daysCount))
userSelection = {'meal':userSelection.meal, 'salad':userSelection.salad, 'sandwich':userSelection.sandwich}
except:
userSelection = {'meal':False, 'salad':False, 'sandwich':False}
userSelection = forms.GetUserMeal(userSelection)
dateDayCorresp[day] = {'date':startWeek + datetime.timedelta(days=daysCount),'userSelection': userSelection}
daysCount += 1
selection_template.html
<form method="post">
<table class="table table-hover table-bordered vertical-align">
<thead>
<tr class="table-primary">
<th rowspan="2">Jour</th>
<th colspan="3">Repas</th>
</tr>
<tr class="table-success">
<th scope="col">Repas</th>
<th scope="col">Salade</th>
<th scope="col">Sandwich</th>
</tr>
</thead>
<tbody>
{% csrf_token %}
{% for day in dateDayCorresp.items %}
<tr>
<th scope="row" class="table-warning">
{{day.0}} ({{day.1.date}})
<!-- {{day.1.userSelection}} -->
</th>
{% for field in day.1.userSelection %}
<td>
<label>{{ field }}</label>
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<button type="submit" class="btn btn-primary btn-lg btn-block fixed-bottom" id="buttonSave">Save</button>
</form>
I have links (which are list of the countries) when I click (for example) "USA" I get list of the cities from other countries too. But I only want the list of the cities in the USA.
Here is my github link. You are welcome to clone and play with it.
https://github.com/ualmaz/post
I tried to filter that like this. queryset = Post.objects.all().values_list(
'city', flat=True).distinct()
But it did not work.
This is my views.py
def cities(request):
queryset = Post.objects.all().values_list(
'city', flat=True).distinct()
context = {
'cities': queryset
}
return render(request, 'users/cities.html', context)
my models.py
class User(AbstractUser):
first_name = models.CharField(verbose_name="First name", max_length=255)
last_name = models.CharField(verbose_name="First name", max_length=255)
country = models.CharField(verbose_name="Country name", max_length=255)
city = models.CharField(verbose_name="City name", max_length=255)
email = models.EmailField(verbose_name="Email", max_length=255)
def __str__(self):
return self.username
class Post(models.Model):
title = models.CharField(max_length=255)
country = models.CharField(max_length=255)
city = models.CharField(max_length=255)
address = models.CharField(max_length=255)
email = models.EmailField(max_length=255)
phone = models.CharField(max_length=255)
website = models.URLField(max_length=255)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('users:blog')
my countries.html (it contains countries list)
{% extends 'shared/base.html' %}
{% load staticfiles %}
{% block content %}
<div class="content-section p-5 mt-5 pl-4">
<table class="table table-hover text-left col-sm-6" style="table-layout: fixed; word-wrap: break-word;">
<tbody>
<tr>
<th>No: </th>
<th>Countries: </th>
</tr>
</tbody>
</table>
{% for post in posts %}
<table class="table table-hover text-left col-sm-6" style="table-layout: fixed; word-wrap: break-word;">
<tbody>
<tr>
<td>{{ post.id }}</td>
<td>{{ post.country }}</td>
</tr>
</tbody>
</table>
{% endfor %}
{% endblock %}
</div>
This is my cities.html (This is where I am having the problem)
{% extends 'shared/base.html' %}
{% load staticfiles %}
{% block content %}
<div class="content-section p-5 mt-5 pl-4">
<table class="table table-hover text-left col-sm-12" style="table-layout: fixed; word-wrap: break-word;">
<tbody>
<tr>
<th style="width: 200px;">No: </th>
<th> Cities: </th>
</tr>
</tbody>
</table>
{% for city in cities %}
<table class="table table-hover text-left col-sm-12" style="table-layout: fixed; word-wrap: break-word;">
<tbody>
<tr>
<td style="width: 200px;">{{ post.pk }}</td>
<td>{{ city }}</td>
</tr>
</tbody>
</table>
{% endfor %}
{% endblock %}
</div>
Your problem is that you are not filtering by the country that you clicked on. In your view, you should pass country in as a parameter. You can then do Post.objects.filter(country=country).values_list('city', flat=True).distinct(), which filters posts by country instead of getting all of the posts.
I have a problem showing fields from another table, where two tables have relationships.
This is my first model:
class DataPribadiSiswa(models.Model):
SiswaID = models.AutoField(primary_key=True)
WaliKelasID = models.CharField(max_length=11, blank=True, null=True)
My second model:
class transaksi_kas(models.Model):
id_kas = models.AutoField(primary_key=True)
siswaID_trans = models.ForeignKey(DataPribadiSiswa, null=True, blank=True)
kelas = models.CharField(max_length=1, null=True, blank=True)
This is my views.py:
def transaksi_index(request):
transaksi = {}
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans')
return render(request, 'kastransaksi/transaksi_index.html', transaksi)
This is the template:
<table id="simple-table" class="table table-striped table-bordered table-hover">
<tr>
<th>No.</th>
<th>Nama</th>
<th>Wali Murid</th>
<th>Kelas</th>
</tr>
{% for kas in transaksikas%}
<tr>
<td>{{ forloop.counter }}</td>
<th>{{ kas.siswaID_trans }}</th>
<td>{{ kas.WaliKelasID }}</td>
<td>{{ kas.kelas }}</td>
</tr>
{% endfor %}
</table>
How do I show {{ kas.WaliKelasID }} from DataPribadiSiswa?
I think you mean to do the following
{{ kas.siswaID_trans.WaliKelasID }}
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans') after this you have to make query get or filter or other.
Example:
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans').get(id=id)
or
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans').filter(your query)
this is link
class Product(models.Model):
name = models.CharField(max_length=50)
desc = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class ProductModels(models.Model):
product = models.ForeignKey(Product)
name = models.CharField(max_length=50)
price = IntegerField(max_length=50)
def __unicode__(self):
return self.name
class Sold(model.Model)
product = models.ForeignKey(Product)
model_name = models.ForeignKey(ProductModels)
sold_date = models.DateField()
model_qty = models.IntegerField()
def __unicode__(self):
return self.sold_date
this is with reference to my previous question( that problem is solved)
what i am trying to find out is how many models have been sold from Jan to Dec for the particular product.
so far i have done this, i know it's little crude. but it would help he if it written correctly:
views.py
allmonths = ['jan' , ....., 'dec']
products = Products.objects.all()
for each_product in products :
models = ProductModels.objects.filter(product = each_product)
for each_model in models:
for months in allmonths :
att_name = str(each_model.model_name) + str(months)
print 'attname %s' % att_name
val = sold.objects.filter(product = each_product ,
model_name = each_model ,(sold_date =(allmonths.indesx(month) + 1))) .aggregate(qty=Sum('model_qty'))
val = temp(val['qty'])
setattr(each_product, att_name , val)
I am not sure if this correct or not , but this approach has worked earlier. i used getattribute template tag from here.
This is how my template looks like :
{% for record in products %}
<tr class="odd gradeX">
<td><span class="label label-warning">{{ record.name }}</span></td>
<td>
<table class="table table-striped table-bordered table-hover" id="pipelineTbl">
{% for model in record.ProductModels_set.all %}
<tr class="odd gradeX">
<td>
<span class="label label-success">{{ model }}</span>
</td>
</tr>
{% endfor %}
</table>
</td>
{% for months in allmonths %}
<td>
<table class="table table-striped table-bordered table-hover" id="pipelineTbl3">
{% for model in record.ProductModels_set.all %}
{% with model|add:months as val %}
<tr>
<td>{{ record|getattribute:val }}</td>
</tr>
{% endwith %}
{% endfor %}
</table>
</td>
{% endfor %}
</tr>
{% endfor %}
You can make the following query:
product = some_product()
year = 2013
product_sells = Sold.objects.filter(product=product, sold_date__year=year)
If you want to know how many individual sells do this:
product_sells.count()
If you want to sum the product sold quantities:
from django.db.models import Sum
product_sells.Sum('model_qty')
In general avoid iterating over Products.objects.all(), as it's really expensive on database and memory.