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 %}
Related
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'm still a beginner in Django and building a management system, I wish to display content from the database using a for loop from 2 tables(GoCustomerRegisration and GoCustomerStatus). But unfortunately, when I iterate over one table the other table brings me only the last element of that table. What I really wish to do is iterate over both tables at once and each element should correspond to it on the other table.
Check out my code below:
something.html
{% for item in detail %}
<tr>
<td>
<a class="text-black text-decoration-none" href="{{ item.photo.url }}">
<img class="rounded-circle me-2" style="object-fit: contain; background-color:#91debb; border:1px solid palegreen;" alt="" width="30" height="30" src="{{ item.photo.url }}"></a>
</td>
<td>
<a class="text-black lg:hover:text-blue-400 text-decoration-none" href="{% url 'customer_detail' pk=item.id %}">{{ item.name }}</a>
</td>
<td class="text-capitalize">{{ item.type }}</td>
<td>{{ item.destination }}</td>
<td>{{ item.age }}</td>
<td>{{ item.time_of_submission }}</td>
<td>
<span>{{ hello.value }}%</span>
<div class="col">
<div class="progress progress-sm">
<div class="progress-bar progress-bar-striped bg-success" aria-valuenow="{{ hello.value }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ h.value }}%;"><span class="visually-hidden"></span>
</div>
</div>
</div>
</td>
{% endfor %}
my views.py
#login_required
def preview(request):
global hello
detail = GoCustomerRegistration.objects.all()
next_event = Event.objects.last()
for i in range(1, (len(detail))+1):
print(i)
hello = GoCustomerStatus.objects.get(name_id=i)
print(hello)
context = {
'detail': detail,
'event': next_event,
'hello': hello,
}
return render(request, 'customers_preview.html', context)
my urls.py
from django.urls import path
urlpatterns = [
path('preview/', preview, name='preview'),
]
my models.py
class GoCustomerRegistration(models.Model):
name = models.CharField(max_length=300, verbose_name='Full name')
email = models.EmailField(null=False)
type = models.CharField(max_length=20, verbose_name='Customer Type')
destination = models.CharField(max_length=30, null=False, verbose_name='Destination')
time_of_submission = models.DateTimeField(auto_now_add=True, null=False, verbose_name=' Submit Time')
phone_number = models.IntegerField(verbose_name='Phone number')
age = models.IntegerField(verbose_name="Age", null=False)
photo = models.ImageField(max_length=10000, verbose_name='Customer Picture',
null=False, upload_to='customers/profiles/')
documents = models.FileField(upload_to='%Y/customers/documents/')
class Meta:
ordering = ["time_of_submission"]
verbose_name = "Customer Registration"
verbose_name_plural = "Customers Registration"
def __str__(self):
return self.name
class GoCustomerStatus(models.Model):
name = models.OneToOneField(GoCustomerRegistration,
max_length=300, verbose_name='Full name',
on_delete=models.CASCADE, primary_key=True,
null=False,
)
value = models.IntegerField(default=0, verbose_name='Level', null=False, primary_key=False)
class Meta:
verbose_name_plural = 'Customers Status'
verbose_name = 'Customer\'s Status'
def __str__(self):
return self.name.name
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 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()
I am new to django and I try to stylize a cell data according to it's value but not working.
The StatusPorumbei model has many objects stored and for each value, I wand another badge class.How can I take each value in StatusPorumbei and giving to it other class? First is the model, next is the template and last is the view function.
class StatusPorumbei(models.Model):
status = models.CharField(max_length=25, null=False, blank=False, unique=True)
def __str__(self):
return self.status
class Meta:
verbose_name = "Status"
verbose_name_plural = "Statusuri"
ordering = ['status']
class Porumbei(models.Model):
id_porumbel = models.AutoField(primary_key=True)
serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True)
anul = models.CharField(max_length=4, null=False, blank=False)
culoare = models.ForeignKey(CuloriPorumbei, on_delete=models.CASCADE, null=False, blank=False)
culoare_ochi = models.ForeignKey(CuloriOchi, on_delete=models.CASCADE, null=False, blank=False)
sex = models.ForeignKey(Gender, on_delete=models.CASCADE)
ecloziune = models.DateField(null=True, blank=True)
rasa = models.CharField(max_length=50, null=True, blank=True)
linie = models.CharField(max_length=50, null=True, blank=True)
nume = models.CharField(max_length=50, null=True, blank=True)
tata = models.CharField(max_length=25, null=True, blank=True)
mama = models.CharField(max_length=25, null=True, blank=True)
compartiment = models.ForeignKey(Compartimente, on_delete=models.CASCADE, null=False, blank=False)
status = models.ForeignKey(StatusPorumbei, on_delete=models.CASCADE, null=False, blank=False)
<tbody>
{% for item in items %}
<tr class="table-active">
<td>{{ item.serie_inel }}</td>
<td>{{ item.anul }}</td>
<td>{{ item.culoare }}</td>
<td>{{ item.sex }}</td>
<td>{{ item.compartiment }}</td>
<td>{{ item.tata }}</td>
<td>{{ item.mama }}</td>
{% if item.status in sts %}
{% if "Activ" %}
<td><span class="badge badge-success">{{ item.status }}</span></td>
{% elif "Reproducător" %}
<td><span class="badge badge-indigo">{{ item.status }}</span></td>
{% endif %}
{% endif %}
<td>
<a href="#" class="mr-25" data-toggle="tooltip" data-original-title="Editare">
<i class="icon-pencil"></i> </a>
</td>
</tr>
{% endfor %}
</tbody>
def dashboard(request):
items = Porumbei.objects.all()
sts = StatusPorumbei.objects.all()
context = {
'items' : items,
'sts' : sts
}
template = loader.get_template("dashboard.html")
return HttpResponse(template.render(context, request))
Query on the item.status
{% if item.status.status == "Activ" %}
<td><span class="badge badge-success">{{ item.status }}</span></td>
{% elif item.status.status == "Reproducător" %}
<td><span class="badge badge-indigo">{{ item.status }}</span></td>
{% else %}
<td><span>{{ item.status.status }}</span></td>
{% endif %}