I was building a django project in that I need to create an edit option for a particular model named SchoolDetail. But while fetching the data from this table using id, its showing the above error
views.py
def SchoolPage(request):
school_details = SchoolDetail.objects.all()
school_details_pk = school_details.id
context = {'school_details': school_details, 'school_details_pk':school_details_pk}
return render(request, 'busschool.html', context)
models.py
class SchoolDetail(models.Model):
school_name = models.CharField(max_length=100, blank= True, null=True)
school_place = models.CharField(max_length=100, blank= True, null=True)
school_email = models.CharField(max_length=100, blank= True, null=True)
school_address = models.CharField(max_length=100, blank= True, null=True)
school_phone = models.CharField(max_length=15, blank= True, null=True)
is_verified = models.BooleanField(default=False)
def __str__(self):
return self.school_name
template
enter code here
<tbody>
{% for i in school_details %}
<tr>
<td>{{i.school_name}}</td>
<td>{{i.school_place}}</td>
<td>{{i.school_email}}</td>
<td>{{i.school_address}}</td>
<td>{{i.school_phone}}</td>
<td>{{i.is_verified}}</td>
<td>click</td>
</tr>
{% endfor %}
<tbody>
The error is due to this row: school_details_pk = school_details.id.
You can refer to the example for the first id:
school_details[0].id
Also iterate over all id in a loop:
for i in school_details:
print(i.id)
Thanks for all answers
I find a solution
<tbody>
{% for i in school_details %}
<tr>
<td>{{i.school_name}}</td>
<td>{{i.school_place}}</td>
<td>{{i.school_email}}</td>
<td>{{i.school_address}}</td>
<td>{{i.school_phone}}</td>
<td>{{i.is_verified}}</td>
<td>click</td>
</tr>
{% endfor %}
</tbody>
Related
I have the following models:
class Supplier(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
class Order(models.Model):
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.supplier.name
#property
def total(self):
orderitems = self.product_set.all()
total = sum([item.get_total for item in products])
return total
class Product(models.Model):
description = models.CharField(max_length=30)
costprice = models.FloatField(null=True, max_length=99, blank=True)
retailprice = models.FloatField(null=True, max_length=99, blank=True)
barcode = models.CharField(
null=True, max_length=99, unique=True, blank=True)
supplier = models.ForeignKey(
Supplier, on_delete=models.CASCADE, default=5)
on_order = models.ForeignKey(
Order, on_delete=models.CASCADE, null=True, blank=True)
on_order_quantity = models.FloatField(null=True, blank=True)
class Meta:
ordering = ('description',)
def __str__(self):
return self.description
i've created an order object for a given supplier with two products, with different quantities and cost prices.
How do I multiply cost x qty and add up those values in order to reach a total order value?
this is my view
def PurchaseOrder(request, pk_order):
orders = Order.objects.get(id=pk_order)
products = Product.objects.filter(
on_order_id=pk_order).prefetch_related('on_order')
total_products = products.count()
supplier = Product.objects.filter(
on_order_id=pk_order).prefetch_related('on_order')
total_value = Product.objects.filter(
on_order_id=pk_order).aggregate(Sum('costprice'))
context = {
'supplier': supplier,
'products': products,
'orders': orders,
'total_products': total_products,
'total_value': total_value, }
return render(request, 'crmapp/purchase_order.html', context)
at the moment it returns this:
This is my html template
It looks like your post is mostly code; please add some more details.'
Well, I need to show my code
{% extends 'crmapp/base.html' %}
{% load static %}
{% block content %}
<div class='main-site>'>
<h4> Supplier: {{orders.supplier}}</h4>
<h5>Order Number: {{orders.id}}</h5>
<h5>Created on: {{orders.date_created | date:"d/m/Y"}}</h5>
<h6>Total Lines In Order: {{total_products}}</h6>
<button style='margin-bottom:10px' class='btn btn-primary' id="open-popup-1">Edit</button>
<button style='margin-bottom:10px' class='btn btn-success' href="" id="open-popup-1">Print/Export</button>
<input type="search" placeholder="Search any field..." class="form-control search-input" data-table="customers-list"/>
<table class="table table js-sort-table mt32 customers-list" id='myTable'>
<thead class="table" >
<tr>
<th class='header' onclick="sortTable(0)" scope="col">ID</th>
<th class='header' onclick="sortTable(1)" scope="col">Description</th>
<th class='header' onclick="sortTable(3)" scope="col">Order Quantity</th>
<th class='header' onclick="sortTable(2)" scope="col">Cost</th>
</tr>
</thead>
<tbody>
<tr>
{% for product in products %}
<td> {{product.id}}</td>
<td><h6><strong>{{product.description}}</strong></h6></td>
<td>{{product.on_order_quantity |floatformat:0}}</td>
<td>£{{product.costprice |floatformat:2}}</td>
</tr>
</tbody>
{% endfor %}
</table>
<div class='ordertotal'>
<h5>Order Value:</h5>
<h6><strong>{{total_value}}</strong></h6>
</div>
</div>
{% endblock %}
Use the property decorator for the costprice field in the Product Model?
class Product(models.Model):
# define other fields here
#property
def costprice(self):
"Returns retailprice * qty for each product."
return self.on_order_quantity * self.retailprice
Update:
There's clearly some misunderstanding. Therefore I'll try to provide more information.
First Question: "How do I multiply cost x qty"
The property decorator allows you to create fields, which behave like calculated read_only fields. (You don't need to initialize them)
#property
def cost_x_qty(self):
"Returns costprice multiplied by qty for each product."
return self.on_order_quantity * self.costprice
Second Question: "How do I add up those values in order to reach a total order value?"
You can use Aggregation to do this.
You can do the following in your view function:
def PurchaseOrder(request, pk_order):
# some code
grand_total = Product.objects.filter(
on_order_id=pk_order).aggregate(Sum('cost_x_qty'))
# add to context
context['grand_total'] = grand_total
return render(request, 'some_template.html', context)
you can use the grand_total in your template file like this:
{{grant_total}}
Hope that helps
I have a contact and an event model where the event model has a foreign key to contact. The first half of my html obviously works, but for some reason when I display the list of other events that the contact has done, I can't get the list to show up. Is it because I'm calling {{event.whatever}} twice on the same page but in two differrent context?
views.py
class EventDetail(DetailView):
template_name = 'crm/eventdetail.html'
model = Event
models.py
class Contact(models.Model):
firstname = models.CharField(max_length=20, null=True, blank=True)
lastname = models.CharField(max_length=20, null=True, blank=True)
email = models.CharField(max_length=40, null=True, blank=True)
phone = models.CharField(max_length=15, null=True, blank=True)
title = models.CharField(max_length=20, null=True, blank=True)
notes = models.CharField(max_length=400, null=True, blank=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["lastname"]
def __str__(self):
return self.firstname
class Event(models.Model):
event_type = models.CharField(max_length=20, choices = event_types)
contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
should_follow_up = models.BooleanField(default=False)
date = models.DateField()
notes = models.CharField(max_length=400)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def get_absolute_url(self):
return reverse('events_detail', kwargs={'pk': self.pk})
eventdetail.html
<div id="container">
<h1> Event: {{event.event_type}} </h1>
<ul>
<li>Event Contact: {{event.contact}}</li>
<li>Created By: {{event.created_by}}</li>
<li>Date: {{event.date}}</li>
<li>Note: {{event.notes}}</li>
</ul>
<h1>Events for {{event.contact}}</h1>
<table class="table">
<tr>
<th scope="col">Event Type</th>
<th scope="col">Date</th>
<th scope="col">3</th>
</tr>
{% for event in contact.event_set.all %}
<tr>
<td> {{event.event_type}}</td>
<td> {{event.date}}</td>
<td> </td>
</tr>
{% endfor %}
</table>
<p>This event was inputted on {{event.created}} and last edited on {{event.updated}}</p>
</div>
The for loop which is supposed to display all the other events the contact has done is not showing up. Any help is appreciated
Changes my view
class EventDetail(DetailView):
def get(self, request, *args, **kwargs):
event = get_object_or_404(Event, pk=kwargs['pk'])
events = event.contact.eventss.all()
context = {'event': event, 'events':events}
return render(request, 'crm/eventdetail.html', context)
Added a related_name to my model
contact = models.ForeignKey(Contact, related_name='eventss', on_delete=models.CASCADE)
Here is the html file that finally worked
{% for events in event.contact.eventss.all %}
<tr>
<td>{{events.event_type}}</td>
<td>{{events.date}}</td>
<td> </td>
</tr>
{% endfor %}
I have basic models for a section, subsection and clause. 1 section can hold multiple subsections. Each subsection can hold multiple clauses. The models look like:
**models.py**
class Clause(models.Model):
number = models.CharField(max_length=8, unique=True)
requirements = models.TextField(max_length=2000, unique=False, blank=True, null=True)
documentation = models.TextField(max_length=2000, unique=False, blank=True, null=True)
class Subsection(models.Model):
number = models.CharField(max_length=5, unique=True)
name = models.CharField(max_length=150, unique=False)
descriptor = models.TextField(max_length=2000, unique=False, blank=True, null=True)
clause = models.ForeignKey(Clause, on_delete=models.DO_NOTHING, related_name="clause")
class Section(models.Model):
number = models.CharField(max_length=2, unique=True)
name = models.CharField(max_length=150, unique=False)
descriptor = models.TextField(max_length=2000, unique=False, blank=True, null=True)
subsection = models.ForeignKey(Subsection, on_delete=models.DO_NOTHING, related_name="subsection")
basic view function to call the desired section:
**views.py**
def main(request):
form = MainSearchForm()
user = request.user
sections = []
show_results = True
if 'query' in request.GET:
show_results = True
query = request.GET['query'].strip()
if len(query) <= 2:
sections = Section.objects.filter(number__iexact=query)
if sections:
records = sections
tpl = "display_console.html"
context = {'user': user, 'records': records, 'form': form}
return render(request, tpl, context)
else:
tpl = "main.html"
context = {'user': user, 'form': form}
return render(request, tpl, context)
unfortunately, I can't get my template to return my subsection data. The following returns a 'Subsection' object is not iterable error:
**template**
<table class="section_tb">
{% if records %}
{% for record in records %}
<tr>
<td>{{ record.number }}</td><td>{{ record.name }}</td>
</tr>
{% for item in record.subsection %}
<tr>
<td>{{ item.number }}</td><td>{{ item.name }}</td>
</tr>
<tr>
<td colspan=2>{{ item.descriptor }}</td>
</tr>
{% endfor %}
</table>
{% endfor %}
{% else %}
{% endif %}
substituting:
{% for item in record.subsection.all %}
for:
{% for item in record.subsection %}
removes the error message, but doesn't return any data. Is there something obvious I'm doing wrong?
This is because Section can have only one Subsection.
So you can access the subsection with just {{record.subsection}} so no forloop needed here.
As a tip remember when you usea one to many, the one is where the foreign key is defined.
The model that store the foreign key will always store only one foreign key.
If you want to access the many foreign keys from the other side use the model_name_in_lowercase_set or define a related name in models.ForeignKey(..., related_name="something") then you can call something_set
I have a Requisition which may have multiple lines. So to implement this I included a unique_together constraint on two fields on the RequisitionLine model which one of the fields is a FK to Requisition . So naturally to pull all the lines of a requisition I would query the RequisitionLine table where the FK = the id of the Requisition model, then iterate over all the sequences to grab all the lines.
My goal is to display the header number with the lines of that requisition under the header in the template but am struggling to accomplish this. I have tried to iterate over the queryset but the code i am posting below is my most recent attempt trying pass lists to the template which is also not working. Right now each header is showing all the lines. Any help would be appreciated.
Models.py
class Requisition(models.Model):
username = models.ForeignKey(
'users.CustomUser', on_delete=models.CASCADE, related_name='req_user')
signature = models.CharField(max_length=10, blank=True, null=True)
class RequisitionLine(models.Model):
parent_req = models.ForeignKey('Requisition', on_delete=models.CASCADE, related_name='par_req_line' )
sequence = models.PositiveIntegerField()
item_code = models.ForeignKey(
'items.ItemMaster', on_delete=models.CASCADE, related_name='req_item', blank=True, null=True)
description = models.CharField(max_length=50, blank=True)
extra_information = models.TextField(blank=True)
quantity = models.PositiveIntegerField(blank=True, default=0,null=True)
price = models.DecimalField(max_digits=19, decimal_places=2, blank=True, default=0.00,null=True)
purchase_order = models.CharField(max_length=9, blank=True,null=True)
po_line = models.PositiveSmallIntegerField(blank=True,null=True)
req_delivery_date = models.DateField(blank=True,null=True)
act_delivar_date = models.DateField(blank=True, null=True)
status = models.ForeignKey('RequisitionStatus', related_name='req_status', on_delete=models.CASCADE, blank=True, null=True)
assistance = models.ForeignKey('users.UserRoles', related_name='req_assist', blank=True, null=True, on_delete=models.CASCADE, limit_choices_to= ~Q(role='Requestor'))
catagory = models.ForeignKey('items.ItemCatagory', on_delete=models.CASCADE, related_name='line_cat', blank=True, null=True)
notes = models.TextField(blank=True)
class Meta:
unique_together = ('parent_req','sequence')
Views.py
def pending_action(request):
user = CustomUser.objects.get(username=request.user)
user_req_headers = Requisition.objects.filter(username=user)
complete_status = RequisitionStatus.objects.get(status='Completed')
req_line_list = []
for req_header in user_req_headers:
req_lines = RequisitionLine.objects.filter(Q(parent_req = req_header) & ~Q(status=complete_status))
req_line_list.append(req_lines)
return render(request, 'req/pending_action.html', {'user_req_headers':user_req_headers,'req_line_list':req_line_list})
pending_action.html
{% for header in user_req_headers %}
<h3>{{header}}</h3>
{% for req_line in req_line_list %}
{% for req in req_line %}
<table>
{% if forloop.first %}
<tr>
<th>description</th>
<th>catagory</th>
</tr>
{% endif %}
<tr>
<!-- FOR LOOP HERE TO ITERATE OF LIST OF QUERYSETS-->
<td>{{ req }}</td>
</tr>
</table>
{% endfor %}
{% endfor %}
{% endfor %}
I solved this problem by creating a queryset of the header and using a reverse relationship to capture the lines associated with each header
<table class="table">
{% for req_header in req_header_list %}
<tr>
<ul>{{ req_header }}
{% for line in req_header.par_req_line.all %}
<li>{{line}}</li>
{% endfor %}
</ul>
</tr>
{% endfor %}
</table>
I have a form field that calls a queryset and uses the 'select' widget.
Is there a way to remove an option value from the queryset if it already has been 'added' to the cart?
In the select form, there's three options: Option A, Option B, Option C.
The user selects Option A, and clicks 'Add'. Now once the user clicks 'Add', I want to remove Option A from the select.
Only Option B and Option C will be available to choose from.
Can this be done just using Django+Python? Or will I need to use additional JS/jQuery?
Thanks!
models.py
class Pickup(models.Model):
# id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, null=True)
total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
status = models.CharField(max_length=120, choices=STATUS_CHOICES, default="Open")
def __str__(self):
return "Pickup Order ID: %s" %(str(self.id))
class PickupItem(models.Model):
pickup = models.ForeignKey('Pickup', null=True, blank=True)
dropoffitem = models.ForeignKey(DropoffItem)
notes = models.TextField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
forms.py
class AddPickupItemForm(forms.ModelForm):
dropoffitem = forms.ModelChoiceField(queryset=DropoffItem.objects.all(), widget=forms.Select(attrs={'class':'form-control'}))
class Meta:
model = PickupItem
fields = ['dropoffitem']
views.py
def add_item_to_pickup_order(request):
request.session.set_expiry(120000)
try:
user = request.user
the_id = request.session['pickup_id']
pickup = Pickup.objects.get(id=the_id)
except:
user = request.user
new_pickup_order = Pickup(user=user)
new_pickup_order.save()
request.session['pickup_id'] = new_pickup_order.id
the_id = new_pickup_order.id
pickup = Pickup.objects.get(id=the_id)
try:
dropoffitem = DropoffItem.objects.get(id=id)
except DropoffItem.DoesNotExist:
pass
except:
pass
form = AddPickupItemForm(request.POST or None)
if request.method == "POST":
dropoffitem_id = int(request.POST['dropoffitem'])
pickup_item = PickupItem.objects.create(pickup=pickup, dropoffitem_id=dropoffitem_id)
pickup_item.save()
return HttpResponseRedirect('%s'%(reverse('add_item_to_pickup_order')))
context = {
"pickup": pickup,
"form": form,
}
return render(request, 'pickups/create_pickup_order.html', context)
.html
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="container">
<div class="col-xs-12">
<h1>Create Cart</h1>
<form method="POST" action="{% url 'add_item_to_pickup_order' %}">
{% csrf_token %}
<table class="table">
<thead>
<th>Item</th>
<th></th>
</thead>
<tr>
<td>{{ form.dropoffitem }}</td>
<td><input type="submit" value="Add Item" class="btn btn-default btn-primary" /></td>
</tr>
</table>
</form>
To exclude/remove an item from the queryset, you can use exclude.
YourModel.objects.exclude(id=4)
To exclude multiple items:
YourModel.objects.exclude(id__in=[4, 6, 10])
More info about exclude on Django docs.