Multiply Django field values to get a total - django

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

Related

How can i get all the product categories a suppliers product belongs

I am working a Supplier Management System. I need to make a particular type of query which I am having issue implementing. I have the user models, and then the user_type which is of two types the suppliers and the admin. Of Course, the filter I need to implement is based of the supplier because only the supplier is able to create product in which they have to specify what categories as well.
My Problem: How can I get all categories a supplier products belongs to.
My Problem Edit: How can get each suppliers products and pass into the templates on the <td> tag
models.py
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
def get_email(self):
return self.email
class user_type(models.Model):
is_admin = models.BooleanField(default=False)
is_supplier = models.BooleanField(default=False)
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
if self.is_supplier == True:
return User.get_email(self.user) + " - is_supplier"
else:
return User.get_email(self.user) + " - is_admin"
#property
def get_categories(self):
return Category.objects.filter(product__user=self.id).distinct()
class Category(models.Model):
name = models.CharField(max_length=256)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=36)
price = models.PositiveIntegerField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
views.py
def Viewsupplier(request):
title = "All Suppliers"
suppliers = User.objects.filter(user_type__is_supplier=True)
categories = Category.objects.filter(product__user='2').distinct()
context = {"suppliers":suppliers, "title":title, "categories":categories}
return render(request, 'core/view-suppliers.html', context)
view-suppliers.html
<table class="table table-borderless table-data3">
<thead>
<tr>
<th>No</th>
<th>Email</th>
<th>Telephone</th>
<th>Category(s)</th>
<th>Country</th>
</tr>
</thead>
<tbody>
{% for supplier in suppliers %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{supplier.email}}</td>
<td>{{supplier.telephone}}</td>
<td>{{supplier.get_categories}}</td>
<td>{{supplier.country}}</td>
</tr>
{% empty %}
<tr><td class="text-center p-5" colspan="7"><h4>No supplier available</h4></td></tr>
{% endfor %}
</tbody>
</table>
You can filter with:
Category.objects.filter(product__user=myuser).distinct()
where myuser is the user you want to filter on.
The .distinct(…) [Django-doc] will prevent returning the same Category that many times as there are Products for that user.

Reverse lookup on template page not working

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 %}

Not getting the value in django template

models.py
class Stock(models.Model):
name = models.CharField(verbose_name='Name of Stock', max_length=300)
purchase_price = models.DecimalField(verbose_name='Purchase Price', blank=True, null=True, max_digits=30, decimal_places=2)
pre_price = models.DecimalField(verbose_name='Last Day Price', blank=True, null=True, max_digits=30, decimal_places=2)
current_price = models.DecimalField(verbose_name='Current Price', blank=True, null=True, max_digits=30, decimal_places=2)
def __str__(self):
return self.name
class StockList(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
stock = models.ForeignKey(Stock)
quantity = models.IntegerField(verbose_name='No.of Shares',default=0)
timestamp = models.DateTimeField(auto_now=True, auto_now_add=False)
def __str__(self):
return str(self.stock)
def market_value_reciever(sender, instance, *args, **kwargs):
purchase_price = instance.stock.purchase_price
quantity = instance.quantity
market_value = purchase_price * quantity
instance.market_value = market_value
print(purchase_price)
print(market_value)
pre_save.connect(market_value_reciever, sender=StockList)
html template
{% for item in queryset %}
<tr>
<td>
{{ item.stock.name }}
</td>
<td>
{{ item.purchase_price }}
</td>
<td>
{{ item.quantity }}
</td>
<td>
{{ item.market_value }}
</td>
</tr>
{% endfor %}
Here I am getting only the value of quantity on html template, purchase price and market value fields are not getting on templates but its values are getting on terminal. Anybody can help, Thank you so much.
You could use the #property decorator in StockList model, so the template can render it:
class StockList(models.Model):
#property
def purchase_price(self):
return self.stock.purchase_price
#property
def market_value(self):
return self.purchase_price * self.quantity

Cannot retrieve foreign key ID

I am building an application that allows a user to create a scenario, then create associated emails, t, calls and trades to the scenario.
There is a 1:many relationship with the scenario and the communications. The issue I am having is I want the user to be able to click the scenario, it then shows the filtered list of communications, each communication source is a tab. The way I am filtering the communication is based on the id of the foreign key on the object. However if there is no entry for the datasource I receive a "no reverse match" because I am using the scenario id from the first object and that doesnt exist if there is no communication for that scenario.
I am stumped on what the best way to do this, besides removing tabs which I like.
Please let me know if I am missing anything, I am relatively new to programming and very new to Django.
models.py
from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse
class Scenario(models.Model):
name = models.CharField(max_length=256, blank=False, null=False, unique=True)
description = models.TextField(max_length=1000)
def get_absolute_url(self):
return reverse('scenarios:detail', kwargs={'pk': self.pk})
def __unicode__(self):
return self.name
class Email(models.Model):
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE )
recipient_email = models.EmailField()
sender_email = models.EmailField()
subject = models.CharField(blank=True, null=False, max_length=256)
body = models.TextField(blank=True, null=False, max_length=2048)
# timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
# updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def get_absolute_url(self):
return reverse('scenarios:email-index')
def __unicode__(self):
return self.sender_email + ' ' + self.recipient_email + ' ' + self.subject
class InstantMessage(models.Model):
NETWORKS = (
('Yahoo', 'Yahoo'),
('MSN', 'MSN'),
('Skype', 'Skype')
)
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
description = models.CharField(max_length=256, null=False, blank=False)
network = models.CharField(max_length=50, null=False, blank=False, choices=NETWORKS)
room = models.CharField(max_length=100, null=False, blank=False)
starttime = models.TimeField(blank=False, null=False)
endtime = models.TimeField(blank=False, null=False)
participant1 = models.CharField(max_length=256, null=False, blank=False)
participant2 = models.CharField(max_length=256, null=False, blank=False)
chatcsv = models.FileField(upload_to='chatfiles')
def get_absolute_url(self):
return reverse('scenarios:im-index')
def __unicode__(self):
return "Network=" + self.network + " Description:" + self.description
class VoiceCall(models.Model):
DIRECTION = (
('outbound', 'Outbound'),
('inbound', 'Inbound')
)
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
description = models.CharField(max_length=256, null=False, blank=False)
direction = models.CharField(choices=DIRECTION, null=False, blank=False, default="Outbound", max_length=15)
starttime = models.TimeField(blank=False, null=False)
endtime = models.TimeField(blank=False, null=False)
traderid = models.CharField(max_length=50,blank=False, null=False)
diallednumber = models.BigIntegerField(blank=True, null=True)
cli = models.BigIntegerField(blank=True, null=True)
nameofcaller = models.CharField(max_length=100, blank=True, null=True)
nameofline = models.CharField(max_length=100, blank=True, null=True)
wavfile = models.FileField(upload_to='voice')
transcript = models.FileField(blank=True, null=True, upload_to='voice')
bagofwords = models.FileField(blank=True, null=True, upload_to='voice')
def get_absolute_url(self):
return reverse('scenarios:call-index')
def __unicode__(self):
return self.description
class Trade(models.Model):
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
tradeprefix = models.CharField(max_length=6, null=False, blank=False)
trader = models.CharField(max_length=256, null=False, blank=False)
sales = models.CharField(max_length=256, null=False, blank=False)
counterpartyid = models.CharField(max_length=256, null=False, blank=False)
counterpartyname = models.CharField(max_length=256, null=False, blank=False)
brokerid = models.CharField(max_length=256, null=False, blank=False)
brokername = models.CharField(max_length=256, null=False, blank=False)
isevent = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse('scenarios:trade-index')
# def __unicode__(self):
# return self.description
class Mobile(models.Model):
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
displayname = models.CharField(max_length=100, null=False, blank=False)
email = models.EmailField()
tonumber = models.BigIntegerField(blank=True, null=True)
fromnumber = models.BigIntegerField(blank=True, null=True)
message = models.CharField(blank=True, null=False, max_length=1024)
def get_absolute_url(self):
return reverse('scenarios:mobile-index')
views.py
class IMScenarioList(generic.ListView):
model = InstantMessage
template_name = 'scenarios/im_filtered.html'
context_object_name = 'scenario_ims'
def get_queryset(self):
return InstantMessage.objects.filter(scenario=self.kwargs['pk'])
class CallScenario(generic.ListView):
model = VoiceCall
template_name = 'scenarios/call_filtered.html'
context_object_name = 'scenario_calls'
def get_queryset(self):
return VoiceCall.objects.filter(scenario=self.kwargs['pk'])
class MobileScenario(generic.ListView):
model = Mobile
template_name = 'scenarios/mobile_filtered.html'
context_object_name = 'scenario_mobiles'
def get_queryset(self):
return Mobile.objects.filter(scenario=self.kwargs['pk'])
class TradeScenario(generic.ListView):
model = Trade
template_name = 'scenarios/trades_filtered.html'
context_object_name = 'trades'
def get_queryset(self):
return Trade.objects.filter(scenario=self.kwargs['pk'])
urls.py
url(r'^(?P<pk>[0-9]+)/email/$', views.EmailScenarioList.as_view(), name='email-scenario'),
# Instant Messages
url(r'^im/$', views.IMList.as_view(), name='im-index'),
url(r'^im/add/$', views.IMCreate.as_view(), name='im-create'),
url(r'^im/(?P<pk>[0-9]+)/update/$', views.IMUpdate.as_view(), name='im-update'),
url(r'^im/(?P<pk>[0-9]+)/delete/$', views.IMDelete.as_view(), name='im-delete'),
url(r'^(?P<pk>[0-9]+)/im/$', views.IMScenarioList.as_view(), name='im-scenario'),
# Voice Calls
url(r'^calls/$', views.CallList.as_view(), name='call-index'),
url(r'calls/add/$', views.CallCreate.as_view(), name='call-create'),
url(r'^calls/(?P<pk>[0-9]+)/update/$', views.CallUpdate.as_view(), name='call-update'),
url(r'^calls/(?P<pk>[0-9]+)/delete/$', views.CallDelete.as_view(), name='call-delete'),
url(r'^(?P<pk>[0-9]+)/voice/$', views.CallScenario.as_view(), name='call-scenario'),
# trades
url(r'^trades/$', views.TradeList.as_view(), name='trade-index'),
url(r'^trades/add/$', views.TradeCreate.as_view(), name='trade-create'),
url(r'^trades/(?P<pk>[0-9]+)/update/$', views.TradeUpdate.as_view(), name='trade-update'),
url(r'^trades/(?P<pk>[0-9]+)/delete/$', views.TradeDelete.as_view(), name='trade-delete'),
url(r'^(?P<pk>[0-9]+)/trade/$', views.TradeScenario.as_view(), name='trade-scenario'),
# mobile
url(r'^mobile/$', views.MobileList.as_view(), name='mobile-index'),
url(r'^mobile/add/$', views.MobileCreate.as_view(), name='mobile-create'),
url(r'^mobile/(?P<pk>[0-9]+)/update/$', views.MobileUpdate.as_view(), name='mobile-update'),
url(r'^mobile/(?P<pk>[0-9]+)/delete/$', views.MobileDelete.as_view(), name='mobile-delete'),
url(r'^(?P<pk>[0-9]+)/mobile/$', views.MobileScenario.as_view(), name='mobile-scenario'),
Templates
trade_index.html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<table id="myTable" class="tablesorter tablesorter-bootstrap">
<thead>
<tr>
<th class="first-name filter-select" data-placeholder="Select a Scenario">Scenario</th>
<th></th>
<th>Trade Prefix</th>
<th>Trader</th>
<th>Sales</th>
<th>Counterparty ID</th>
<th class="first-name filter-select" data-placeholder="Select Counterparty">Counterparty Name</th>
<th>Broker ID</th>
<th></th>
<th class="first-name filter-select" data-placeholder="Select Broker">Broker Name</th>
<th class="first-name filter-select" data-placeholder="IsEvent">IsEvent</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for trade in trades %}
<tr>
<td data-toggle="tooltip" title="Description: {{trade.scenario.description}}">{{trade.scenario}}</td>
<td></td>
<td>{{trade.tradeprefix}}</td>
<td>{{trade.trader}}</td>
<td>{{trade.sales}}</td>
<td>{{trade.counterpartyid}}</td>
<td>{{trade.counterpartyname}}</td>
<td>{{trade.brokerid}}</td>
<td></td>
<td>{{trade.brokername}}</td>
<td>{{trade.isevent}}</td>
<td>
<a href="{% url 'scenarios:trade-update' trade.id %}">
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-pencil" />
</button>
</a>
</td>
<td><form action="{% url 'scenarios:trade-delete' pk=trade.id %}" method="post">
{% csrf_token %}
<input type="hidden" name="call_id" value="{{ trade.id}}"/>
<button type="submit" class="btn btn-default btn-sm" onclick="return confirm('Are you sure you want to delete {{trade.description}}?')">
<span class="glyphicon glyphicon-trash" />
</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<a href="{% url 'scenarios:trade-create' %}">
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-plus" />
</button>
</a> Add Trade
<br>
<button type="button" class="btn btn-default btn-sm" value="Back" onClick="javascript:history.go(-1);">
<span class="glyphicon glyphicon-backward" />
</button>
</div>
{% endblock %}
trades_filtered.html
{% extends 'scenarios/trade_index.html' %}
{% block content %}
{% with trades|first as first_trade %}
<ul class="nav nav-pills">
<li class="active">trades</li>
<li>emails</li>
<li>instant messages</li>
<li>voice</li>
<li>mobile</li>
</ul>
{% endwith %}
{{ block.super }}
{% endblock %}
Right now in trades_filtered.html you take the ID of a given scenario and use that ID to manually construct your five URLs. If it were me, I'd use a custom model method to determine whether or not we need to generate a URL first.
class Scenario(models.Model):
name = models.CharField(max_length=256, blank=False, null=False, unique=True)
description = models.TextField(max_length=1000)
def generate_trade_url(self):
if self.trade_set.exists():
return reverse('scenarios:trade-scenario', kwargs={'pk':self.pk})
return None
def generate_email_url(self):
...
You would need one method like this for each URL you want to generate. You can this use this logic either in the view (preferable) or in your template (simpler but slower) to dynamically generate your URLs only when they are valid.
EDIT: I just looked at this answer a second time. I included null=False in the name field definition because it was in the original, but be aware that it doesn't actually do anything useful on a CharField. Django doesn't use null values for those fields, instead storing them as '' (empty string).

Django -- Removing an option from queryset form field if already selected

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.