At the very beginning I would note that I'm a beginner as hel :P I have two models in my django models.py and I want them to display on a page. The issue is that I got error about no possible iteration and I don't know why.
Also, I'm following the Crash Course from Youtube with changing some thing for my use :)
Could You please advice as I haven't found any useful tips on google?
Thanks!
models.py
from django.db import models
# Create your models here.
class Supplier(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Order(models.Model):
STATUS = (
('Pending Order', 'Pending Order'),
('Pending PR', 'Pending PR'),
('Declined by SME', 'Declined by SME'),
('Declined by Finance', 'Declined by Finance'),
('Ordered', 'Ordered'),
('Canceled', 'Canceled'),
('Delivered', 'Delivered'),
)
product = models.CharField(max_length=200, null=True)
link = models.CharField(max_length=400, null=True)
supplier = models.ForeignKey(Supplier, null=True, on_delete=models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, default='Pending Order', choices=STATUS)
amount = models.CharField(max_length=40, null=True)
comment = models.CharField(max_length=400, null=True, blank=True)
requester = models.CharField(max_length=40, null=True)
def __str__(self):
return self.product
views.py
from django.shortcuts import render
from .models import *
# Create your views here.
def home(request):
return render(request, 'accounts/dashboard.html')
def products(request):
return render(request, 'accounts/products.html')
def customer(request):
return render(request, 'accounts/customer.html')
def orders(request):
orders = Order.objects.all()
customers = Supplier.objects.all()
context = {'orders': orders, 'customers': customers}
return render(request, 'accounts/orders.html', {'orders': Order})
And a part of my HTML which is only bootstrap and HTML
<table class="table table-sm">
<tr>
<th>Supplier</th>
<th>Product (Name)</th>
<th>Product (ID)</th>
<th>Date Orderd</th>
<th>Status</th>
<th>Requester</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders %}
<tr>
<td>{{order.supplier}}</td>
<td>{{order.product}}</td>
<td>{{order.link}}</td>
<td>{{order.date_created}}</td>
<td>{{order.status}}</td>
<td>{{order.requester}}</td>
{% endfor %}
</table>
def orders(request):
orders = Order.objects.all()
customers = Supplier.objects.all()
context = {'orders': orders, 'customers': customers}
return render(request, 'accounts/orders.html', context)
Try this.
In render you're passing the Order class instead of your queryset orders
Related
I would like to change the data that is in this column from a form but I can't display the data and save them and also add a delete button. anyone have a solution.
models.py
class Employe(models.Model):
Matricule = models.CharField(max_length=10, null=False)
Prenom = models.CharField(max_length=40, null=True)
Nom = models.CharField(max_length=40, null=True)
Tel = models.CharField(max_length=20, null=True)
Adresse = models.CharField(max_length=100, null=True)
Courriel = models.CharField(max_length=100, null=True)
Horaire = models.CharField(max_length=50, null=True)
Date_embauche = models.CharField(max_length=100, null=True)
UtilisateurOSP = models.CharField(max_length=100, null=True)
MotdepasseOSP = models.CharField(max_length=50, null=True)
Anciennete = models.CharField(max_length=10, null=True)
data_created = models.DateTimeField(auto_now_add=True, null=True)
class Disciplinaire(models.Model):
employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL)
Avis_verbal = models.CharField(max_length=300, null=True)
Avis_ecrit = models.CharField(max_length=300, null=True)
Avis_ecrit2 = models.CharField(max_length=300, null=True)
Suspension = models.CharField(max_length=300, null=True)
Fin_emploie = models.CharField(max_length=300, null=True)
data_created = models.DateTimeField(auto_now_add=True, null=True)
forms.py
class disciplinaireForm(ModelForm):
class Meta:
model = Disciplinaire
fields = '__all__'
views.py
def updateDisciplinaire(request, id):
emp = Disciplinaire.filter()
forms = disciplinaireForm(instance=emp)
if request.method == 'POST':
forms = disciplinaireForm(request.POST, instance=emp)
if forms.is_valid():
forms.save()
return redirect('/')
context = {'forms':forms}
return render(request, 'accounts/updateDisciplinaire.html', context)
page.html
<th scope="col">Avis Verbal</th>
<th scope="col">1er Avis Écrit</th>
<th scope="col">2e Avis Écrit</th>
<th scope="col">Suspension</th>
<th scope="col">Fin d'emploi</th>
<th scope="col">Action</th>
</tr>
{% for j in disci %}
<tr>
<td>{{j.Avis_verbal}}</td>
<td>{{j.Avis_ecrit}}</td>
<td>{{j.Avis_ecrit2}}</td>
<td>{{j.Suspension}}</td>
<td>{{j.Fin_emploie}}</td>
<td><a class="btn btn-outline-info" href="{% url 'updateDisciplinaire' j.id %}">Modifier</a>
</tr>
{% endfor %}
data and button
error message
The error says that in line 102 from your views.py you are trying to filter something. If you want to filter try:
emp_all = Disciplinaire.objects.filter(employe = id)
for emp in emp_all:
print(emp.Matricule)
you need to put how to filter, by which field.
When you use filter it will get you a queryset, a list of records not just one single record, if you want a single record you can use get:
emp = Disciplinaire.objects.get(employe = id)
I am trying to perform below process in my Django application:
Adding member to 'Member' table whenever a user registers.
Creating tasks to populate 'Task' table.
Allocating the 'unallocated tasks' to member and hence populating Allocation table.
I see the data submitted is passed through request.POST but my table is not updated with the same data.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Member(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
DESIGNATION = [
('Developer', 'Developer'),
('Tester', 'Tester'),
('Support', 'Support'),
]
name = models.CharField(max_length=200, null=True)
role = models.CharField(max_length=100, null=True, choices=DESIGNATION)
email = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
class Task(models.Model):
CATEGORY = [
( 'Low', 'Low'),
('Medium', 'Medium'),
('Urgent', 'Urgent'),
]
STATUS = [
('Not Started', 'Not Started'),
('In Progress', 'In Progress'),
('Completed', 'Completed'),
]
name = models.CharField(max_length=200, null=True)
category = models.CharField(max_length=200, null=True, choices=CATEGORY)
description = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
member = models.ForeignKey('Member', null=True, on_delete=models.SET_NULL)
task_status = models.CharField(max_length=200, null=True, choices=STATUS)
def __str__(self):
return self.name
class Allocation(models.Model):
member = models.ForeignKey('Member', null=True, on_delete=models.SET_NULL)
task = models.OneToOneField('Task', null=True, primary_key=True, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.task.name
views.py
def allocate_task(request):
try:
unallocated_tasks = Task.objects.get(member__isnull=True)
except Task.DoesNotExist:
unallocated_tasks = None
if unallocated_tasks == None:
return redirect('error')
else:
form = TaskAllocateForm(instance=unallocated_tasks)
if request.method == 'POST':
form = TaskAllocateForm(request.POST, instance=unallocated_tasks)
if form.is_valid():
form.save()
return redirect('/')
context = {
'form':form,
}
return render(request, 'ttt/allocate_task.html', context)
forms.py
class TaskAllocateForm(ModelForm):
class Meta:
model = Task
fields = '__all__'
html file
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p> Allocate tasks </p>
{{ form.as_table }}
<input type="submit" name="Submit"></input>
</form>
Does it have to do something with my model definitions of Allocation model??
I have two models which I want to output on a template. But only if the parent class object matches to the child class object.
{% for market in markets %}
{% if object.market|slugify == market.market %}
>>> DO SOMETHING <<<
{% endif %}
{% endfor %}
The problem is when I use slugify on the Object it's giving me a string which starts with a small letter but market.market outputs a string with a capital letter.
Do someone know a solid solution for that?
UPDATE:
my Views:
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_context_data(self, **kwargs):
context = super(ItemDetailView, self).get_context_data(**kwargs)
context['markets'] = Market.objects.all()
# And so on for more models
return context
def market_list(request):
context ={
'markets': Market.objects.all()
}
return render(request, "market-list.html", context)
My Models:
class Market(models.Model):
market = models.CharField(max_length=30)
branch = models.CharField(choices=BRANCH_CHOICES, max_length=1)
image = models.ImageField(blank=True)
slug = models.SlugField(blank=True)
def __str__(self):
return self.market
def get_absolute_url(self):
return reverse("core:market-product-list", kwargs={
'slug': self.slug
})
class Item(models.Model):
title = models.CharField(max_length=100)
market = models.ForeignKey(Market, related_name='children', on_delete=models.CASCADE, blank=True, null=True)
price = models.FloatField()
discount_price = models.FloatField(blank=True, null=True)
category = models.ForeignKey(ItemCategory, related_name='children', on_delete=models.CASCADE, blank=True, null=True)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
description = models.TextField()
image = models.ImageField()
def __str__(self):
return self.title
I am trying to print all the orders related to a specific customer. I used a for loop to access my orders in the html file, and i used an if statement to make sure that the order is related to the customer.
{% for order in orders %}
{% if customer.name == order %}
{{ order }}
{% endif %}
{% endfor %}
in my views I gave my html file access to these variables.
def orderss(request, pk):
Customer = customer.objects.get(id=pk)
orders = Order.objects.all()
context = {
'customer':Customer,
'orders': orders,
}
return render(request, 'Inventory_Management/orders.html', context)
to reach this page i used a button
View Orders
the url is the one below
path('orders/<str:pk>/', orderss, name="orderss")
related models
class Order(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out for delivery', 'Out for delivery'),
('Delivered', 'Delivered'),
)
order_head = models.ForeignKey(order_header, blank=False, null=True, on_delete=models.SET_NULL)
items = models.ForeignKey(item, blank=False, null=True, on_delete=models.SET_NULL)
Quantity = models.CharField(max_length=100)
date_created = models.DateTimeField(auto_now_add=True, null=True)
total = models.CharField(max_length=100)
status = models.CharField(max_length=200, null=True, choices=STATUS)
def __str__(self):
return '{self.order_head.Buyer}'.format(self=self)
class customer(models.Model):
name = models.CharField(max_length=12, blank=False)
phone = models.CharField(max_length=12, blank=False)
email = models.CharField(max_length=50, blank=False)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
class order_header(models.Model):
date_created = models.DateTimeField(auto_now_add=True, null=True)
User = models.CharField(max_length=100, blank=False, default="Seller")
Type = models.CharField(max_length=100, default="cash")
Buyer = models.ForeignKey(customer, blank=True, null=True, on_delete=models.SET_NULL)
Note = models.CharField(max_length=100, blank=True, default="Discount: ")
Order_Id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
def __str__(self):
return 'Order Customer: {self.Buyer}, Order Id: {self.Order_Id}'.format(self=self)
now the problem is no orders appear when I press the button, all i get is a blank page even though the specific customer has a number of orders. Help appreciated! Please Help!
In template you're trying to compare name field that is string with object (Order). I guess you thought that name will be compared with order string representation using __str__ method.
Try this:
views.py
Customer = customer.objects.get(id=pk)
orders = order_header.objects.filter(Buyer=Customer)
context = {'orders': orders}
template
{% for order_head in orders %}
{% for order in order_head.order_set.all %}
{{ order }}
{% endfor %}
{% endfor %}
I have two models that feed one view.
models.py
class Item(models.Model):
item_name = models.CharField(max_length=100)
item_type = models.ForeignKey(Item_type, on_delete=models.SET_NULL, null=True)
owned_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)****
added_at = models.DateTimeField('date item added')
updated_at = models.DateTimeField('last update')
def __str__(self):
return self.item_name
class Item_status(models.Model):
item = models.ForeignKey(Item, on_delete=models.SET_NULL, null=True)
borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
loaned_at = models.DateTimeField(default=None, blank=True, null=True)
due_back = models.DateTimeField(default=None, blank=True, null=True)
def __time__(self):
return self.loaned_at
def itemname(self):
return (self.item.item_name)
I have the following view
views.py
class LoanedItemsByUserListView(LoginRequiredMixin,generic.ListView):
model = Item_status
template_name ='catalog/item_status_list_borrowed_user.html'
paginate_by = 10
def get_queryset(self):
return Item_status.objects.filter(borrower=self.request.user).order_by('due_back')
def get_context_data(self, **kwargs):
context = super(LoanedItemsByUserListView, self).get_context_data(**kwargs)
context['Owned_list'] = Item.objects.filter(owned_by=self.request.user, item_type = 1)
context['Loaned_list'] = Item_status.objects.exclude(borrower=self.request.user).exclude(borrower__isnull=True)
return context
I would like to find the cross section of the 'Owned_list' and the 'Loaned_list' in a single template
Something like
<h2>Loaned Books</h2>
{% if Owned_list %}
<ul>
{% for thing in Owned_list.item_name and in Loned_list.item.item_name %}
<li>
{{thing}}
</li>
{% endfor %}
</ul
{% else %}
<p>There are no books in the library.</p>
{% endif %}
I have take a look at the django documentation here https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-display/, and around SO but not found exactly what I am looking for.
Thanks!