I'm trying to render the name of all the products in templates. How do I do that in dashboard.html in the code given below? It is simple in ForeignKey but i cannot figure it out in ManyToMany Relationship.Please help
Models.py
class Product(models.Model):
CATEGORY=(('INDOOR','Indoor'),('OUTDOOR','Outdoor'))
name=models.CharField(max_length=100)
category=models.CharField(max_length=20,
choices=CATEGORY,
blank=True,
default='INDOOR',
help_text='Item Category',)
date_created=models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
class Order(models.Model):
STATUS=(('PENDING','Pending'),('OUT FOR DELIVERY','Out For Delivery'),('DELIVERED','Delivered'))
customer=models.ForeignKey(Customer,null=True,on_delete=models.SET_NULL)
date_created=models.DateTimeField(default=timezone.now)
product=models.ManyToManyField(Product)
status=models.CharField(max_length=20,
choices=STATUS,
blank=True,
default='PENDING',
help_text='Delivery Status',)
def __str__(self):
return self.customer.first_name
views.py
def home(request):
order=Order.objects.all()
context={
'order':order,
}
return render(request,'accounts/dashboard.html',context)
dashboard.html
<tr>
<th>Product</th>
<th>Date Orderd</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{%for i in order%}
<tr>
<td>{{i}}</td> //in this line
<td>{{i.date_created}}</td>
<td>{{i.status}}</td>
<td><button>Update</button> </td>
<td> <button>Update</button></td>
</tr>
{%endfor%}
I am assuming that the first model in Model.py is your Product class (you forgot to past the class name):
In your template replace:
<td>{{ i }}</td>
for
{% for product in order.product.all %}
<td>{{ product.name }}</td>
{% endfor %}
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've ran into a little problem. I want to construct a proper queryset to get values which represent the number of the expenses per category to display this like that.
This is what I got now:
class CategoryListView(ListView):
model = Category
paginate_by = 5
def get_context_data(self, *, category_object_list=None, **kwargs):
**categories = Category.objects.annotate(Count('expense'))
queryset = categories.values('expense__count')**
return super().get_context_data(
category_object_list=queryset,
**kwargs)
Of course it doesnt work and I have terrible table like this. I suppose the problem isn't in HTML but in my absolutely wrong query... What should I do?
This is my HTML in case it would be needed:
{% for category in object_list %}
<tr>
<td>
{{ category.name|default:"-" }}
</td>
<td>
{% for number in category_object_list %}
{{ number.expense__count }}
{% endfor %}
</td>
<td>
edit
delete
</td>
{% endfor %}
</tr>
Also my models.py:
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return f'{self.name}'
class Expense(models.Model):
class Meta:
ordering = ('-date', '-pk')
category = models.ForeignKey(Category, null=True, blank=True,
on_delete=models.CASCADE)
name = models.CharField(max_length=50)
amount = models.DecimalField(max_digits=8, decimal_places=2)
date = models.DateField(default=datetime.date.today, db_index=True)
def __str__(self):
return f'{self.date} {self.name} {self.amount}'
You can try like this within your template with the reverse look up of
Foregin Keys. See the docs for more detail.
{% for category in object_list %}
<tr>
<td>
{{ category.name|default:"-" }}
</td>
<td>
{{category.expense_set.all.count}}
</td>
<td>
edit
delete
</td>
{% endfor %}
</tr>
Now in the view you can just pass all the categories with the ListView
class CategoryListView(ListView):
model = Category
paginate_by = 5
i'm pretty new to django and i'm struggling with models and database but i managed to get some stuff right but this here isnt working out for me.
so basically what i want to do is when i click on a course it shows me a table with the students who are registered to this course but i keep getting an empty table
models.py
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils.text import slugify
User = get_user_model()
# Create your models here
class student (models.Model):
S_id = models.IntegerField(unique=True)
S_fname = models.CharField(max_length=255)
S_lname = models.CharField(max_length=255)
def __str__(self):
return self.S_id
class classes(models.Model):
C_id = models.CharField(max_length=255,unique=True)
C_name = models.CharField(max_length=255)
C_room = models.CharField(max_length=255)
Start_time = models.CharField(max_length=255)
Instructs = models.ManyToManyField(User, through='Teaches')
Registered = models.ManyToManyField(student, through='Registered')
slug = models.SlugField(allow_unicode=True, unique=True)
def __str__(self):
return self.C_id
def save(self,*args,**kwargs):
self.slug = slugify(self.C_id)
super().save(*args,**kwargs)
def get_absolute_url(self):
return reverse('classes:single',kwargs={'slug':self.slug})
class Meta:
ordering = ['C_name']
class Teaches(models.Model):
Instructor = models.ForeignKey(User, related_name='St_id', on_delete=models.CASCADE)
Course = models.ForeignKey(classes, related_name='Co_id', on_delete=models.CASCADE)
class Registered(models.Model):
Student = models.ForeignKey(student, related_name='Stu_id', on_delete=models.CASCADE)
Course = models.ForeignKey(classes, related_name='Cou_id', on_delete=models.CASCADE)
classes_detail.html
{% extends "classes/classes_base.html" %} {% block pregroup %}
<div class="container">
<h1>{{classes.C_name}}</h1>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Student ID</th>
<th>Student First Name</th>
<th>Student Last Name</th>
<th>attendance</th>
</tr>
</thead>
<tbody>
{% for student in object_list %}
{% if student in classes.Registered.all %}
<tr class="">
<td>{{ student.S_id }}</td>
<td>{{ student.S_fname }}</td>
<td>{{ student.S_lname }}</td>
<td></td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock pregroup %}
views.py
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin,PermissionRequiredMixin
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.views import generic
from .models import classes,Teaches
from django.contrib import messages
# Create your views here.
class ListClasses(generic.ListView):
model = classes
class SingleClass(generic.DetailView):
model = classes
This is what your classes details template should look like:
{% for student in object.Registered.all %}
<tr class="">
<td>{{ student.S_id }}</td>
<td>{{ student.S_fname }}</td>
<td>{{ student.S_lname }}</td>
<td></td>
</tr>
{% endfor %}
I am trying to show a detailed view of the contacts stored in a phonebook. The PhoneBook(id, name) is one of my models which is a foreign key to model Contact(id, first_name, last_name, phone_number, phone_book).
In my index page, there is a button which opens the phone book. After that, I want it such that the user may click on a phone book and the detailed view(first_name, last_name, phone_number) would be shown to them.
In view.py, I have a function which captures all the phonebook, passes it through context(dict). In my template, I have used a for loop to go through all the phonebooks and print them.
I am unable to direct the page to a detailed view. How do I get the phonebook the user clicked on? And how to direct the page from ./view to ./detail
# view.py
def view_phone_book(request):
all_phone_books = PhoneBook.objects.all()
context = {
'all_phone_books': all_phone_books
}
return render(request, "CallCenter/view_phone_book.html", context)
def detailed_view_phone_book(request):
all_contacts = Contact.objects.all().filter(phone_book=phone_book_user_clicked_on)
context = {
'all_contacts': all_contacts
}
return render(request, "CallCenter/detailed_view_phone_book.html", context)
# urls.py
urlpatterns = [
path('', index, name="index"),
path('create/', create_phone_book, name="create"),
path('add/', add_to_phone_book, name="add"),
path('view/', view_phone_book, name="view"),
path('detail/', detailed_view_phone_book, name="detailed_view")
]
# models.py
class PhoneBook(models.Model):
"""
Model to store customer to a phone book
"""
name = models.CharField(max_length=10, blank=False)
def __str__(self):
return self.name
class Contact(models.Model):
"""
Model to store customer to a phone book.
"""
first_name = models.CharField(max_length=50, blank=False)
last_name = models.CharField(max_length=50, blank=False)
phone_number = models.CharField(max_length=13, blank=False, unique=True)
phone_book = models.ForeignKey(PhoneBook, on_delete=models.CASCADE)
def __str__(self):
return self.phone_number
<!--view_phone_book.html-->
<table>
<tr>
<th>Phone Book</th>
</tr>
{% for phone_book in all_phone_books %}
<tr>
<form method="get" action="../detail/"><td>{{ phone_book }} </td></form>
</tr>
{% endfor %}
</table>
<!--detailed_view_phone_book.html-->
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
</tr>
{% for phone_detail in all_phone_detail %}
<tr>
<form>
<td>{{ phone_detail.first_name }}</td>
<td>{{ phone_detail.last_name }}</td>
<td>{{ phone_detail.phone_number }}</td>
</form>
</tr>
{% endfor %}
</table>
I am unable to go from ./view to ./detail. Also, how would I know which phone book the user clicked on?
I figured it out on how to make it work, and I'm answering it so that if anyone gets stuck in, it can help themselves.
# views.py
def view_phone_book(request):
all_phone_books = PhoneBook.objects.all()
context = {
'all_phone_books': all_phone_books
}
return render(request, "CallCenter/view_phone_book.html", context)
def detailed_view_phone_book(request, phone_book_id):
try:
all_contacts = Contact.objects.filter(pk=phone_book_id)
except Contact.DoesNotExist:
raise Http404("PhoneBook Does Not Exist!")
context = {
'all_contacts': all_contacts
}
return render(request, "CallCenter/detailed_view_phone_book.html", context)
#urls.py
urlpatterns = [
path('', index, name="index"),
path('create/', create_phone_book, name="create"),
path('add/', add_to_phone_book, name="add"),
path('campaign/', create_campaign, name="create-campaign"),
path('view/', view_phone_book, name="view-phone-book"),
path('detail/<int:phone_book_id>', detailed_view_phone_book, name="detail-view-phone-book"),
<!--view_phone_book.html-->
<body>
{% for phone_book in all_phone_books%}
{{ phone_book }}
<br>
{% endfor %}
Back To Home
</body>
<!--detailed_view_phone_book.html-->
{% if all_contacts %}
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
</tr>
{% for contact in all_contacts %}
<tr>
<form>
<td>{{ contact.first_name }}</td>
<td>{{ contact.last_name }}</td>
<td>{{ contact.phone_number }}</td>
</form>
</tr>
{% endfor %}
</table>
{% endif %}
Back To Home
I watched the Brain's CS50 video, which helped me. I'll suggest you do the same. He explains the concepts in a beginner-friendly way.
I could'nt solve it. I want to pass specific datas from model to template.
I had tried something could'nt figure it out.Can anyone help me out , should I need to write logic to view.py or is there easy way to pass data.
class Receipt(models.Model):
amount = models.DecimalField(max_digits=5, decimal_places=2)
vat = models.DecimalField(max_digits=5, decimal_places=2)
total_amount = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return str(self.total_amount)
#My view.py
class IndexView(TemplateView):
template_name = "index.html"
model = Receipt
class DetailView(TemplateView):
template_name = "detail.html"
model = ReceiptItem
#index.html
<div class="panel panel-default">
<div class="panel-heading">Market</div>
<table class="table">
<tr>
{% for amount in objects %}
<td>{{ amount }}</td>
<td>{{ vat }}</td>
<td>{{ total_amount }}</td>
{% endfor %}
</tr>
</table>
</div>
TemplateView does not provide support for models. If you want a list of all of the objects so you can loop over them you will want a ListView, then switch your for loop to be:
{% for amount in object_list %}
https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-display/