I want to show all orders in a table of my panel but its not showing.Its showing in django admin but not showing in my panel.
Here is my Views.py:
class AdminPanel(View):
def get(self, request):
products = Product.get_all_products()
cats = Category.get_categories()
orders = Order.get_all_orders()
args = {'products':products, 'cats':cats, 'orders':orders}
return render(self.request, 'adminpanel/main.html', args)
Here is my HTML file:
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Sno.</th>
<th scope="col">Date</th>
<th scope="col">Invoice ID</th>
<th scope="col">Customer Name</th>
<th scope="col">Phone Number</th>
<th scope="col">Product Quantity</th>
<th scope="col">Status</th>
<th scope="col">Total</th>
</tr>
</thead>
<tbody>
{% for order in orders %}
{% if orders %}
<tr>
<th scope="row">{{forloop.counter}}</th>
<td>{{order.date}}</td>
<td>GNG#{{order.id}}</td>
<td>{{order.fname}}</td>
<td>{{order.phone}}</td>
<td>{{order.quantity}}</td>
<td>{{order.status}}</td>
<td>{{order.price}}</td>
</tr>
{% else %}
<h5 class="badge badge-danger">No Orders Found</h5>
{%endif%}
{% endfor %}
</tbody>
</table>
in my model.py I have this method:
#staticmethod
def get_all_orders(self):
return Order.objects.all()
Model:
class Order(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product")
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
fname = models.CharField(max_length=100, null=True)
address = models.CharField(max_length=1000, null=True)
phone = models.CharField(max_length=12, null=True)
price = models.IntegerField()
date = models.DateField(datetime.datetime.today, null=True)
status = models.ForeignKey(Status, on_delete=models.CASCADE, blank=True, null=True)
#staticmethod
def get_all_orders(self):
return Order.objects.all()
Here i didnt put orders variable in the right function
So the function will look like this ::
def admin(request):
orders = Order.objects.all()
params = {'orders':orders}
return render(request, 'adminpanel/mani.html', params)
The function get_all_orders is useless. It does nothing special. Just use in the View:
orders = Order.objects.all()
Related
I'm beginner to Django. I want to ask how can I get the addresses of all the Dials that are in DataUpload table from BO table. It doesn't return any data in Customer_Address column in HTML.
class DataUpload(models.Model):
Dial = models.IntegerField()
Customer_Address = models.ForeignKey(BO, on_delete=models.CASCADE,
null=True,blank=True, related_name='address')
National_ID = models.IntegerField()
Customer_ID = models.IntegerField()
Status = models.CharField(max_length=100)
Registration_Date = models.DateTimeField(max_length=100)
Is_Documented = models.CharField(max_length=100, null=True)
BO Model:
class BO(models.Model):
id = models.AutoField(primary_key=True)
Dial = models.IntegerField()
Customer_Address = models.CharField(max_length=100, null=True, blank=True)
Wallet_Limit_profile = models.CharField(max_length=100, null=True, blank=True)
View:
def listing(request):
data = DataUpload.objects.all()
paginator = Paginator(data, 10) # Show 25 contacts per page.
page_number = request.GET.get('page')
paged_listing = paginator.get_page(page_number)
# print(data)
return render(request, 'pages/listing.html', {'paged_listing': paged_listing, 'range': range})
When I call item.Customer_Address it does return any data and no errors are appearing, also I tried item.Customer_Address_id.Customer_Address same thing.
HTML:
{% for item in paged_listing %}
<tr>
<td class="text-center align-middle">{{ item.Dial }}</td>
<td class="text-center align-middle">{{ item.Customer_Address}}</td>
<td class="text-center align-middle">{{ item.National_ID }}</td>
<td class="text-center align-middle">{{ item.Status }}</td>-->
<!-- <td>Edit </td> -->
<td class="text-center align-middle"> <button class="btn btn-primary"><a class="edit-link"
href="{% url 'edit_record' item.id %}">Edit</button> </a> </td>
</tr>
{% endfor %}
customer/update_order.html
<table class="table table-striped table-bordered">
<form method="POST" action=".">
{% csrf_token %}
<tr>
<th style="width:160px;text-align:center;background-color: blue;color:red;">食物</th>
<th style="width:100px;text-align:center;background-color: blue;color:red;">單價</th>
<th style="width:100px;text-align:center;background-color: blue;color:red;">數量</th>
<th style="width:100px;text-align:center;background-color: blue;color:red;">總價</th>
<th style="width:100px;text-align:center;background-color: blue;color:red;"></th>
</tr>
{% for item in food %}
<tr>
<td style="text-align:center;vertical-align:middle;">
{{ item.product.name }}
</td>
<td style="text-align:center;vertical-align:middle;">$ {{ item.unit_price }}</td>
<td style="text-align:center;vertical-align:middle;">
<input name="qty{{ item.id }}" type="text" value="{{ item.quantity }}">
</td>
<td style="text-align:center;vertical-align:middle;">
更新
</td>
<td style="text-align:center;vertical-align:middle;">$ {{ item.total_price }}</td>
</tr>
{% endfor %}
<tr>
<td colspan="4" align="left" class="upline"><strong>總計</strong></td>
<td align="center" class="upline">$ {{ order.total_price }} (包括$100運費)</td>
</tr>
<tr>
<td colspan="4" align="left" class="upline"><strong>換領積分</strong></td>
<td align="center" class="upline">{{ order.points_earned }}</td>
</tr>
</form>
</table>
views.py
def update_order(request,order_id):
global cartlist_update
order = Order.objects.get(id=order_id)
food = OrderDetail.objects.filter(order=order)
cartlist_update = []
for item in food:
cart = []
menu_food = Menu.objects.get(name=item.product.name)
food_name = OrderDetail.objects.get(product=menu_food)
cart.append(food_name.product.name)
cart.append(food_name.unit_price)
cart.append(food_name.quantity)
cart.append(food_name.total_price)
print(cart)
cartlist_update.append(item)
print(cartlist_update)
context = {'order':order,'food':food}
return render(request,'customer/update_order.html',context)
def update_item_qty(request,item_id):
global cartlist_update
menu = OrderDetail.objects.get(id=item_id)
print(menu.id)
qty_id = 'qty'+str(menu.id)
print(qty_id)
new_quantity = request.POST.get(qty_id,'')
print(new_quantity)
order_id = menu.order.id
## original_food = menu.product.name
price = menu.unit_price
return redirect('update_order',order_id=order_id)
models.py
class Driver(models.Model):
user = models.ForeignKey(User,models.CASCADE)
name = models.CharField(max_length=100,null=True,blank=True)
## orders = models.ManyToManyField('Order',related_name='driver_orders')
mobile = models.IntegerField(null=True,blank=True)
email = models.CharField(max_length=200,null=True,blank=True)
approval = models.BooleanField(default=False)
## profile_pic = models.ImageField(upload_to='staff_profile/',null=True,blank=True)
## points = models.IntegerField(default=0)
date = models.DateTimeField(auto_now_add=True,null=True,blank=True)
def __str__(self):
return self.name
class Menu(models.Model):
name = models.CharField(max_length=100)
restaurant = models.ForeignKey(Restaurant,models.CASCADE)
photo = models.ImageField(upload_to='menu/')
price = models.DecimalField(decimal_places=2,max_digits=7)
def __str__(self):
return self.name
class Order(models.Model):
PAYMENT_OPTIONS = (
('VISA','VISA'),
('Master','Master'),
('Octopus','Octopus'),
('Cash','Cash'),
)
STATUS = (
('Pending','Pending'),
('Approved','Approved'),
('On the way','On the way'),
('Delivered','Delivered'),
('Completed','Completed'),
)
METHODS = (
('外賣自取','外賣自取'),
('送遞','送遞'),
)
user = models.ForeignKey(User,models.CASCADE,null=True,blank=True)
customer = models.CharField(max_length=200,null=True,blank=True)
card_id = models.IntegerField(null=True,blank=True)
code = models.CharField(max_length=10,null=True,blank=True)
mobile = models.IntegerField(null=True,blank=True)
email = models.CharField(max_length=200,null=True,blank=True)
total_price = models.DecimalField(decimal_places=2,max_digits=7)
payment_method = models.CharField(max_length=50,choices=PAYMENT_OPTIONS,null=True,blank=True)
driver = models.ForeignKey(Driver,models.CASCADE,null=True,blank=True)
status = models.CharField(max_length=50,choices=STATUS,default='Pending')
take_method = models.CharField(max_length=50,choices=METHODS,null=True,blank=True)
points_earned = models.IntegerField(default=0)
date = models.DateTimeField(auto_now_add=True)
address = models.CharField(max_length=350,null=True,blank=True)
## def save(self,commit=True):
## new_order = super(Order,self).save(commit=False)
## new_order.code = 'K00'+str(self.new_order.id)
## if commit:
## new_order.save()
def __str__(self):
return str(self.customer)+'\'s Order'
class OrderDetail(models.Model):
order = models.ForeignKey(Order,models.CASCADE)
product = models.ForeignKey(Menu,models.CASCADE)
unit_price = models.IntegerField(default=0)
quantity = models.IntegerField(default=0)
total_price = models.IntegerField(default=0)
def __str__(self):
return str(self.order.customer)+'\'s --- '+str(self.product.name)+' x '+str(self.quantity)
I am trying to run the update_item_qty view after I click the hyperlink. However if I try to print out the result with request.POST.get('qty'+str(menu.id),''), it returns empty instead of the value that I put on the input field name called 'qty'+str(menu.id) even though I had included the form inside. Can anyone show me where is the problem?
You can access the variables in the POST request by looping all key value pairs in your post request.
views.py
def update_item_qty(request,item_id):
# Loop over all key value pairs in the POST request.
for k, v in request.POST.items():
# Check if the key starts with qty
if k.startswith('qty'):
# Get the item id and the quantity
item_id = k.split('qty')[1]
quantity = v
print(f'The item {item_id} has the quantity {v}.'}
I use Django 3.2.7 and I would like to query all orders from a customer.
Models.py
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)
product = models.ForeignKey(Product,null=True, on_delete=models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
Views.py
def customer(request,pk):
customer = Customer.objects.get(id=pk)
orders = customer.order_set.all()
my_context={
'customer':customer,
'orders':orders
}
return render(request, 'accounts/customer.html', context=my_context)
Urls.py
path('customer/<str:pk>/', views.customer),
Template
{% for order in orders %}
<tr>
<td>
{order.product}
</td>
<td>
{order.product.category}
</td>
<td>
{order.date_created}
</td>
<td>
{order.status}
</td>
<td>Update</td>
<td>Delete</td>
</tr>
{% endfor %}
My problem is that instead of printing the actual data on the template is prints the query data.
I think the problem is at
orders = customer.order_set.all()
What am I doing wrong?
I want to have template page with object(orders) list (another list, for another user). Like relations one to many. Where do i need to define that objects(order)(for exemple by id: order_id=1 and order_id=3) is assigned to user(driver) with id=1 etc?
I was trying to create Driver class and than set atribute driver in order Class like this.
form.py
class OrderForm(forms.Form):
telephone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'.")
airport = forms.ChoiceField(choices=AIRPORT_CHOICES) ### Jeśli lotnisko jest celem podróży
direction = forms.ChoiceField(choices=DIRECTION_CHOICES) ## to pick_up < plane i odwrotnie!!!
adress = forms.CharField()
client = forms.CharField()
telephone = forms.CharField(validators=[telephone_regex])
flight_number = forms.CharField()
plane = forms.DateTimeField(input_formats=['%Y-%m-%d'])
pick_up = forms.DateTimeField(input_formats=['%Y-%m-%d'])
gate = forms.CharField()
company = forms.ChoiceField(choices=COMPANY_CHOICES)
driver = forms.ChoiceField(choices=DRIVER_CHOICES)
models.py
class Driver(models.Model):
name = models.CharField(max_length=30)
tel = models.CharField(max_length=17)
class Order(models.Model):
telephone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format:
'+999999999'.")
airport = models.CharField(max_length=10, choices=AIRPORT_CHOICES)
direction = models.CharField(max_length=7, choices=DIRECTION_CHOICES)
adress = models.CharField(max_length=100, null=False, blank=False)
client = models.CharField(max_length=50, null=False, blank=False)
telephone = models.CharField(validators=[telephone_regex], max_length=17, blank=False)
flight_number = models.CharField(max_length=7)
plane = models.DateTimeField(null=True)
pick_up = models.DateTimeField(null=True)
gate = models.CharField(max_length=10, null=True, blank=True)
comapny = models.CharField(max_length=50, choices=COMPANY_CHOICES)
driver = models.ForeignKey(Driver, on_delete=models.CASCADE)
order_list.html
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<h1>Hi {{ user.username }}! Have a good tips!</h1>
{% else %}
<h1>You have to login to see your orders list</h1>
{% endif %}
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">client</th>
<th scope="col">telephone</th>
<th scope="col">flight number</th>
<th scope="col">airport</th>
<th scope="col">direction</th>
<th scope="col">adress</th>
<th scope="col">gate</th>
<th scope="col">plane</th>
<th scope="col">pick up</th>
</tr>
</thead>
{% for order in orders %}
<tbody>
<tr>
<th scope="row">{{ order.id }}</th>
<td>{{ order.client }}</td>
<td>{{ order.telephone }}</td>
<td>{{ order.flight_number }}</td>
<td>{{ order.airport }}</td>
<td>{{ order.direction }}</td>
<td>{{ order.adress }}</td>
<td>{{ order.gate }}</td>
<td>{{ order.plane }}</td>
<td>{{ order.pick_up }}</td>
<td>{{ order.driver }}</td>
</tr>
</tbody>
{% endfor %}
</table>
{% endblock %}
views.py
class OrderView(View):
def get(self, request, id):
orders = Order.objects.get(id=id)
users = User.object.get(id=id)
ctx = {
'orders': orders,
'users': users
}
return render(request, 'order.html', ctx)
class OrderListView(View):
def get(self, request):
form = OrderForm()
orders = Order.objects.all()
ctx = {'form': form, 'orders': orders}
return render(request, 'orders/order_list.html', ctx)
class AddOrderView(View):
def get(self, request):
form = OrderForm()
return render(request, 'orders/add_order.html', {'form': form})
def post(self, request, *args, **kwargs):
form = OrderForm(request.POST)
if form.is_valid():
order = Order.objects.create(airport=form.cleaned_data['airport'],
direction=form.cleaned_data['direction'],
adress=form.cleaned_data['adress'],
client=form.cleaned_data['client'],
telephone=form.cleaned_data['telephone'],
flight_number=form.cleaned_data['flight_number'],
plane=form.cleaned_data['plane'],
pick_up=form.cleaned_data['pick_up'],
gate=form.cleaned_data['gate'],
driver=form.cleaned_data['driver'])
return render(request, 'orders/add_order.html', {'form': form})
I expect to get form when i can input new order and select driver but I'm geting this:
http://dpaste.com/0PD363H
I am using Django 1.11 and Python3.5
I have created a table. This is a screenshot.
When I got a table from my query database, it is showing 10+2+3... but I want to get total sum value for every customer within Due Taka update column in table like this 10+2+4+2 = 18
this is my model.py file
class CustomerInfo(models.Model):
customer_name = models.CharField('Customer Name', max_length=100)
customer_mobile_no = models.CharField(
'Mobile No', null=True, blank=True, max_length=12)
customer_price=models.IntegerField('Customer Price',default=1)
customer_product_warrenty = models.CharField('Product Warrenty',null=True, blank=True,max_length=10)
customer_sell_date = models.DateTimeField('date-published', auto_now_add=True)
customer_product_id=models.CharField('Product ID',max_length=300,null=True, blank=True)
customer_product_name=models.TextField('Product Name')
customer_product_quantity=models.IntegerField('Quantity',default=1)
customer_uid = models.CharField(max_length=6, blank=True, null=True)
customer_info=models.TextField('Customer Details Informations', blank=True, null=True)
customer_conditions=models.CharField('Conditions',blank=True, null=True, max_length=300)
customer_due_taka_info=models.IntegerField(default=0)
customer_discount_taka=models.IntegerField(default=0)
customer_first_time_payment=models.IntegerField('First Time Payment',default=0)
customer_first_due_info = models.CharField('First Due Info',default='No due info', max_length=200, blank=True, null=True)
customer_product_mrp=models.IntegerField('Products MRP', default=0)
customers_refrence=models.CharField(max_length=100)
customer_updated = models.DateTimeField(auto_now=True)
customer_type=models.CharField('Customer Type', default='MobilePhone', max_length=50)
def __str__(self):
return self.customer_name
def remainBalance(self):
if self.customer_price > self.customer_due_taka_info:
remain=self.customer_price - self.customer_due_taka_info
return remain
def totalRetalsPerSingle(self):
return self.customer_product_quantity * self.customer_product_mrp
#def product_warrenty(self):
#expire_date_oneyr =self.customer_sell_date+ datetime.timedelta(days=365)
#return 'This product expire on this date ' + str(expire_date_oneyr)
class Meta:
verbose_name = ("গ্রাহকের তথ্য")
verbose_name_plural = ("গ্রাহকের তথ্যসমূহ")
#intregated with Customerinfo Model (Using foreignKey)
class DueTaka(models.Model):
customer_due = models.IntegerField('Due Taka', default=0)
customer_due_date=models.DateTimeField(auto_now_add=True)
customer_due_info=models.CharField('Due Info', max_length=200, blank=True, null=True)
customerinfo = models.ForeignKey(CustomerInfo, on_delete=models.CASCADE)
due_customer_updated = models.DateTimeField(auto_now=True)
def __int__(self):
return self.customer_due
def sum_total(self):
return self.customer_due
this is my views.py file
due_update_info = CustomerInfo.objects.filter(duetaka__customer_due_date__range=(starts_date, tomorrow)).order_by('-customer_updated')
I want to get total price customer_due fields within DueTaka model for per single customer. if a customer name is 'asad'. He has some multple due taka and he paid multiple times like this 10+20+20 Now I want to get total value like 50
If I update my customer's profile, same customers name come again with in loop my table. But I don't want this.
and this is my html template file
<h1>Due Paid Book</h1>
<table class="table table-hover table-bordered">
<p style="font-size:16px;">Due Paid Tody</p>
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Invoice ID</th>
<th>Mobile</th>
<th>Product</th>
<th>Product MRP</th>
<th>Customer Paid (TK)</th>
<th>Due Amount</th>
<th>Total Price</th>
<th>Warrenty</th>
<th>Purchase Date</th>
<th>Due Taka update</th>
<th>Update Date</th>
<th>QN</th>
</tr>
</thead>
{% for x in due_update_info %}
<tbody>
<tr>
.......code in here.......
<td>
{% for y in x.duetaka_set.all %}
{{y.customer_due | intcomma}}+
{% endfor %}
{{x.duetaka_set }}
<!--i want to toatal value in here, now nothing showing-->
{{total_price}}
</td>
</tr>
<tr>
</tr>
</tbody>
{% endfor %}
<td colspan="10"></td>
<td> Total Du Paid <br> <i>{{starts_date}} to {{end_date}}</i> </td>
<td> <b>{{dupaid_today|intcomma}} TK</b> </td>
</table>
Now How can I implement in views file?
Maybe change the filter query like this this:
CustomerInfo.objects.filter(duetaka__customer_due_date__range=(starts_date, tomorrow)).annotate(due_taka_total=Sum('duetaka__customer_due')).order_by('-customer_updated')
which will give you additional field 'due_taka_total', which can be used in template, like:
{{ y.due_taka_total }}
assuming y is an object of CustomerInfo
OR
You could write a custom template tag and find out the total using it:
from django import template
register = template.Library()
#register.simple_tag
def get_total_taka(customer_info_object):
return sum([each.customer_due for each in customer_info_object.duetaka_set.all()])
and use it in template like this:
{% get_total_taka y %}
assuming y is an object of Customerinfo
For writing the custom template tag refer: Writing Custom Tags