How to render queryset in django template - django

Hi Im using this code for rendering
def ShowContent(dic, htmlpage):
plantilla = get_template(htmlpage)
c = Context(dic)
renderizado = plantilla.render(c)
return HttpResponse(renderizado)
and I wanna represent this Query, so I use 'AllQuery' dict for 'todas.html'.
def ShowAll(request):
AllQuery = Actividad.objects.all().order_by('fecha')
print AllQuery
return ShowContent(AllQuery, 'todas.html')
I don't know how to represent it in my template
<tr>
<td></td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
Actividad from models.py
class Actividad(models.Model):
id_evento = models.IntegerField(primary_key=True)
titulo = models.CharField(max_length=100)
tipo_evento = models.CharField(max_length=50)
gratis = models.BooleanField(default=False)
fecha = models.DateField()
hora = models.TimeField()
largo = models.BooleanField(default=False)
url = models.URLField(max_length=128)
any idea? I think its easy but I'm not gettin it. I'm trying this:
{% for i in AllQuery %}
{ AllQuery.i.titulo }
{% endfor %}
from views, I can access doing
def ShowAll(request):
AllQuery = Actividad.objects.all().order_by('fecha')
print AllQuery[0].titulo

Just use a generic list view, this will make your life a lot easier and save some time.
class ListView(generic.ListView)
model=Actividad
template_name='todas.html'
and then in your template you can display the list like so
{% for i in object_list %}
{{ i.titulo }}
{% endfor %}

Related

Why data from table is not recieving in django?

When I tried to retrieve data from table it is not showing anything without giving error message.
This is my model
class staff(models.Model):
id = models.AutoField
name = models.CharField(max_length=250)
role = models.CharField(max_length=250)
salary = models.CharField(max_length=250)
address = models.CharField(max_length=250)
number = models.CharField(max_length=250)
date = models.DateField()
This is my views file
def user(request):
staffs = staff.objects.all()
params = {'staff': staffs}
return render(request, "salary/user.html", params)
and this is my template
<td> 02312 </td>
{% for staff in staffs %}
<td>{{ staff.name }} </td>
{% endfor %}
<td> $14,500 </td>
try this
views.py
def user(request):
staffs = staff.objects.all()
return render(request, "salary/user.html", {'staff': staffs})
html
<td> 02312 </td>
{% for staffs in staff %}
<td>{{ staffs.name }} </td>
{% endfor %}
<td> $14,500 </td>

How can I capture the name or reg_no of the book in this list?

I'm working on a library system. I am unable to get the registration number of a book/books to be returned back to library...
My intention is to click on Return which captures the book name for return processing.. With what I have, when I print(book) it returns None meaning nothing has been taken from the click
My models
class Books(models.Model):
DEPARTMENT = (
('COM', 'Computer'),
('ELX', 'Electronics'),
('CIV', 'Civil'),
('BBS', 'Business'),
('MSC', 'Miscellaneous'),
)
reg_no = models.CharField(max_length=20, blank=True)
book_name = models.CharField(max_length=200)
no_of_books = models.IntegerField()
book_detail = models.TextField(default='text')
department = models.CharField(max_length=3, choices=DEPARTMENT)
def Claimbook(self):
if self.no_of_books>1:
self.no_of_books=self.no_of_books-1
self.save()
else:
print("not enough books to Claim")
def Addbook(self):
self.no_of_books=self.no_of_books+1
self.save()
def __str__(self):
return self.book_name
class Return(models.Model):
return_date = models.DateField(default=datetime.date.today)
borrowed_item = models.ForeignKey(Issue,on_delete=models.CASCADE)
def new_issue(request):
if request.method == 'POST':
i_form = IssueForm(request.POST)
if i_form.is_valid():
name = i_form.cleaned_data['borrower_id']
book = i_form.cleaned_data['book_id']
i_form.save(commit=True)
books = Books.objects.get(book_name=book)#Get a book names as selected in the dropdown
semest = Student.objects.get(name=name).semester#Get a student with a semester as selected in the dropdown
departm = Student.objects.get(name=name).depart
Books.Claimbook(books)
return redirect('new_issue')
else:
i_form = IssueForm()
semest = None
departm = None
sem_book = Semester.objects.filter(sem=semest, depart=departm)
return render(request, 'libman/new_issue.html', {'i_form': i_form, 'sem_book': sem_book})
The return view
def return_book(request):
book = request.GET.get('book_pk')
print(book)
books = Books.objects.get(id=book)
#b_id = r_form.cleaned_data['borrower_id']
Books.Addbook(books)
Issue.objects.filter(borrower_id=1, id=book).delete()
return render(request,'libman/view_issue.html',{'issue':issue})
The template that displays the borrowed books with a link to return beside each book.
{% if issue %}
<table class="layout">
<thead>
<th>Reg No.</th>
<th>Student Name</th>
<th>Book Name</th>
<th>Issue Date</th>
<th>Action</th>
</thead>
{% for borrow in issue %}
<tr>
<td>{{ borrow.borrower_id.student_id }}</td>
<td>{{ borrow.borrower_id }}</td>
<td>{{ borrow.book_id }}</td>
<td>{{ borrow.issue_date }}</td>
<td name='book_pk'>Return </td>
</tr>
{% endfor %}
</table>
{% else %}
<p> There are no books registered. </p>
{% endif %}
Issue model
class Issue(models.Model):
borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE)
book_id = models.ForeignKey(Books,on_delete=models.CASCADE)
issue_date = models.DateField(default=datetime.date.today)
def __str__(self):
return str(self.book_id)
if i understood correctly - I believe you need to pass the borrow.book_id to the return view. so the return view knows which book you want return
in your template add the variable book_pk as follows
<td name='book_pk'>Return </td>
also you need to update your urls.py file to accept the new variable something like this
urlpatterns = [
path('returnbook/<book_pk>/', return_book),
]
but the above will need to also update your view function to handle the new passed argument and fetch the object etc..
def return_book(request,book_pk):
Or
you can add a form with a submit button
<form action="{% url 'return_book' %}">
<label for="book_id">Borrowed Book_id</label>
<input type="text" id="book_id" name="book_pk" value="{{ borrow.book_id }}" disabled><br><br>
<input type="submit" value="Submit">
</form>
it should work with your current code i think

Django Formset Delete Field Not Showing

I need to manually render my formset in my template and I cannot get the delete checkbox field into the template when I render manually. However, it does show when I render {{form.as_table}}.
views.py
QuoteManifestForm= modelformset_factory(QuoteManifest, QManifestForm, can_delete = True)
template - this does not display the {{form.DELETE}} but every other field shows fine, including id which I can see in the DOM.
{{ manifest.management_form }} <--!I passed QuoteManifestForm to template as 'manifest'-->
{% for form in manifest.forms %}
<div id="form_set">
<table id = 'manifest-table25' class="manifest-table2" width=100%>
{% csrf_token %}
<tbody width=100%>
<tr class="manifest-row">
<td width = 17.5% class="productCode" onchange="populateProduct(this)">{{form.ProductCode}}</td>
<td width = 32.5% class="description">{{form.DescriptionOfGoods}}</td>
<td width = 12.5% class="quantity" oninput="calculateUnit(this)">{{form.UnitQty}}</td>
<td width = 12.5% class="unitType">{{form.Type}}</td>
<td width = 12.5% class="price" oninput="calculate(this)">{{form.Price}}</td>
<td width = 12.5% class="amount2">{{form.Amount}}</td>
<td>{{form.DELETE}}</td>
{{form.id}}
</tr>
</tbody>
</table>
</div>
{% endfor %}
Any idea why that is not working?
UPDATE:
I found in the django docs that if you are rendering manually, you should include something like the below in your form. I tried this, but still no Delete field appears in my template:
{% if form2.can_delete %}
<td> {{form.DELETE}}</td>
{% endif %}
CODE TO REPRODUCE
views.py
def QuoteView(request):
QuoteManifestForm= modelformset_factory(QuoteManifest, fields =('ProductCode', 'DescriptionOfGoods', 'UnitQty', 'Type','Amount', 'Price'), can_delete = True)
if request.method == "POST":
form2 = QuoteManifestForm(request.POST)
form2.save()
return redirect('HomeView')
else:
form2 = QuoteManifestForm()
context = {
'form2': form2,
}
return render(request, 'quote.html', context)
quote.html
{{ form2.management_form }}
<div id="form_set">
{% for form2 in form2.forms %}
<table id = 'manifest-table25' class="manifest-table2" width=100%>
{% csrf_token %}
<tbody width=100%>
<tr class="manifest-row">
<td width = 17.5% class="productCode" onchange="populateProduct(this)">{{form2.ProductCode}}</td>
<td width = 32.5% class="description">{{form2.DescriptionOfGoods}}</td>
<td width = 12.5% class="quantity" oninput="calculateUnit(this)">{{form2.UnitQty}}</td>
<td width = 12.5% class="unitType">{{form2.Type}}</td>
<td width = 10.5% class="price" oninput="calculate(this)">{{form2.Price}}</td>
<td width = 12.5% class="amount2">{{form2.Amount}}</td>
<td>{{form2.DELETE}}</td>
{{form2.id}}
</tr>
</tbody>
</table>
{% endfor %}
</div>
models.py
class QuoteManifest(models.Model):
ProductCode = models.ForeignKey(Product, null=True, blank=True)
DescriptionOfGoods = models.CharField(max_length=500, blank=True)
UnitQty = models.CharField(max_length=10, blank=True)
Type = models.CharField(max_length=50, blank=True)
Amount = models.CharField(max_length=100, blank=True)
Price = models.CharField(max_length=100, blank=True)
{{form2.DELETE}} is supposed to render a checkbox. This is what I cannot get working. It does work when I render the form as {{form2.as_p}} but that will not work for me in my case.
Using your example code, I was able to create a sample that seems to render the checkbox using the {{ form.DELETE }} syntax.
It appears that my sample code is very similar to what you already have. I did add an on_delete parameter to the ProductCode variable in the QuoteManifest model. And I'm not sure what your Product model looks like so I just created a dummy model. I also removed your CSS classes and JavaScript calls. Is it possible that something in your JavaScript was overriding the checkboxes?
As you'll see in my sample, I do get the checkbox. My code is below, and here is a link to the working demo on repl.it.
models.py
from django.db import models
class Product(models.Model):
ProductName = models.CharField(max_length=100, unique=True)
class QuoteManifest(models.Model):
ProductCode = models.ForeignKey(Product, null=True, blank=True, on_delete=models.CASCADE)
DescriptionOfGoods = models.CharField(max_length=500, blank=True)
UnitQty = models.CharField(max_length=10, blank=True)
Type = models.CharField(max_length=50, blank=True)
Amount = models.CharField(max_length=100, blank=True)
Price = models.CharField(max_length=100, blank=True)
views.py
from django.shortcuts import render, redirect
from django.forms.models import modelformset_factory
from .models import QuoteManifest
def QuoteView(request):
QuoteManifestForm= modelformset_factory(QuoteManifest, fields =('ProductCode', 'DescriptionOfGoods', 'UnitQty', 'Type','Amount', 'Price'), can_delete=True)
form2 = QuoteManifestForm()
context = {
'form2': form2,
}
return render(request, 'quote.html', context)
templates/quote.html
<div id="form_set">
{% for form2 in form2.forms %}
<table id="manifest-table25" width=100%>
{% csrf_token %}
<tbody width=100%>
<tr>
<td>{{form2.ProductCode}}</td>
<td>{{form2.DescriptionOfGoods}}</td>
<td>{{form2.UnitQty}}</td>
<td>{{form2.Type}}</td>
<td>{{form2.Price}}</td>
<td>{{form2.Amount}}</td>
<td>{{form2.DELETE}}</td>
</tr>
</tbody>
</table>
{% endfor %}
</div>
Based on the examples here: https://docs.djangoproject.com/en/3.0/topics/forms/formsets/#manually-rendered-can-delete-and-can-order
It looks like your view would be:
def QuoteView(request):
QuoteManifestFormset= modelformset_factory(QuoteManifest, fields =('ProductCode', 'DescriptionOfGoods', 'UnitQty', 'Type','Amount', 'Price'), can_delete = True) # Renamed as formset for clarity
if request.method == "POST":
formset = QuoteManifestFormset(request.POST) # also renamed
formset.save()
return redirect('HomeView')
else:
formset = QuoteManifestFormset()
context = {'formset': formset}
return render(request, 'quote.html', context)
And your quote.html I think {% for form2 in form2.forms %} needs to be {% for form in formset %}
<form method="post">
{{ formset.management_form }}
{% for form in formset %}
<table id = 'manifest-table25' class="manifest-table2" width=100%>
{% csrf_token %}
<tbody width=100%>
<tr class="manifest-row">
<td width = 17.5% class="productCode" onchange="populateProduct(this)">{{form.ProductCode}}</td>
<td width = 32.5% class="description">{{form.DescriptionOfGoods}}</td>
<td width = 12.5% class="quantity" oninput="calculateUnit(this)">{{form.UnitQty}}</td>
<td width = 12.5% class="unitType">{{form.Type}}</td>
<td width = 10.5% class="price" oninput="calculate(this)">{{form.Price}}</td>
<td width = 12.5% class="amount2">{{form.Amount}}</td>
<td>{{form.DELETE}}</td>
{{form.id}}
</tr>
</tbody>
</table>
{% endfor %}
</form>

Print a project name in jinja template

I have the following models
AcsObject class
class AcsObjects(models.Model):
object_id = models.IntegerField(primary_key=True)
object_type = models.ForeignKey('AcsObjectTypes', db_column='object_type')
context = models.ForeignKey('self', blank=True, null=True)
security_inherit_p = models.BooleanField()
creation_user = models.IntegerField(blank=True, null=True)
Projects class
class ImProjects(models.Model):
project = models.ForeignKey('AcsObjects',related_name='project', on_delete=False, primary_key=True)
project_name = models.CharField(max_length=1000)
project_nr = models.CharField(max_length=100)
project_path = models.CharField(max_length=100)
TimesheetTasks class
class TimesheetTasks(models.Model):
task = models.ForeignKey('Projects', related_name='t_task', on_delete=False, primary_key=True)
uom = models.ForeignKey('Categories', related_name='u_uom', on_delete=False)
planned_units = models.FloatField(blank=True, null=True)
billable_units = models.FloatField(blank=True, null=True)
I wrote the following code into views.py file.
class TimesheetData(TemplateView):
template_name = 'timesheet.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["da"] = TimesheetTasks.objects.all()
return context
I want to print a project_name but it is giving me a task_id ( task_id and project_id are same) using jinja template.
timesheet.html
<body>
<p> {{da}} </p>
<table class="table table-light">
<thead class="thead-light">
<tr>
<th>Task </th>
</tr>
</thead>
<tbody>
{% for timesheet in da %}
<tr>
<td> {{timesheet.task}} </td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
It is giving me a blank output
Output
That's simply just because you're not access to product_name field yet.
<tbody>
{% for timesheet in da %}
<tr>
<td> {{timesheet.task}} </td>
</tr>
{% endfor %}
</tbody>
With this, Jinja just render the task id (project id), because Jinja think that you're not need any other information but just the foreign key value. So to be able to see the project_name, you should use this instead: timesheet.task.project_name, it does the job.
<tbody>
{% for timesheet in da %}
<tr>
<td> {{timesheet.task.project_name}} </td>
</tr>
{% endfor %}
</tbody>
Just want to mention that this could lead to another issue (performance issue) when Jinja have to query the data when render the template. To get rid of that, consider to use select_related which is an API of Django Queryset, check it out and gain some experiment that API, it really useful when using Django.

Django model cross reference in templatre

Ok So my mind is going to mush...
I have 2 models. One is a card location and the other holds card types. I've got a view and template which display's the cards in a specific chassis. What I can't seem to get to work is the foreign key reference. I want to display the CardType.sName in the template.
I'm certain i've just done something stupid ...
Models.py:
class CardLocation(models.Model):
chassis = models.ForeignKey(Chassis)
slot = models.CharField(max_length=20)
slot_sub = models.CharField(max_length=20)
CardType = models.ForeignKey(CardType)
PartNum = models.CharField(max_length=200)
ProdID = models.CharField(max_length=200)
versID = models.CharField(max_length=200)
serialNum = models.CharField(max_length=200)
cleiCode = models.CharField(max_length=200)
lastSeen = models.DateTimeField()
isActive = models.BooleanField(default=0)
def __unicode__(self):
return self.slot
class CardType(models.Model):
sName = models.CharField(max_length=5)
lName = models.CharField(max_length=200)
description = models.CharField(max_length=200)
def __unicode__(self):
return self.sName
views.py
class DetailView(generic.ListView):
model = CardLocation
template_name = 'chassis/detail.html'
context_object_name = 'cardLoc'
def get_queryset(self):
#chassis_id = get_object_or_404(CardLocation, chassis_id__iexact=self.args[0])
chassis_id = self.args[0]
return CardLocation.objects.filter(chassis_id=chassis_id)
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(DetailView, self).get_context_data(**kwargs)
# Add in the
context['chassisQ'] = Chassis.objects.get(id=self.args[0])
#context['CardType'] = CardType.objects.order_by()
return context
detail.html
{% load staticfiles %}
<h2>
<table>
<tr><td>Name:</td><td>{{ chassisQ.name }}<td></tr>
<tr><td>Owner:</td><td>{{ chassisQ.owner }}<td></tr>
<tr><td>ip Adress:</td><td>{{ chassisQ.ipAddr }}<td></tr>
<tr><td>Last updated:</td><td>{{ chassisQ.lastSeen }}<td></tr>
</table>
</h2>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% if cardLoc %}
<table border=1>
<tr><td>slot</td><td>Type</td><td>Part Number</td><td>Product ID/</td><td>Version ID</td><td>Serial Num</td><td>CLEI code</td></tr>
{% for card in cardLoc %}
<tr>
<td align="right">{{ card.slot }}</td>
<td>Type {{ card.cardtype__set.all.sName }} </td> <!-- DISPLAY sName HERE -->
<td>{{ card.PartNum }}</td>
<td align="right">{{ card.ProdID }}/</td>
<td align="left">{{ card.versID }}</td>
<td>{{ card.serialNum }}</td>
<td>{{ card.cleiCode }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>No cards are available...</p>
{% endif %}
A Card has numerous CardTypes (as it's a ForeignKey relationship), not just one. You have:
<td>Type {{ card.cardtype__set.all.sName }} </td>
You need to loop through all the CardTypes related to the Card:
{% for card in cardLoc %}
...
{% for cardtype in card.cardtype__set.all %}
<td>Type {{ cardtype.sName }}</td>
{% endfor %}
...
{% endfor %}