class Product(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True)
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99)
image = models.ImageField(upload_to=upload_image_path,null=True, blank=True)
featured = models.BooleanField(default=False)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True)
class OrderItem(models.Model):
item = models.ForeignKey(Product, on_delete=models.CASCADE )
quantity = models.IntegerField(default=1)
item_cart = models.CharField(max_length=20, null=True, blank=True)
active = models.BooleanField(default=True)
class Cart(models.Model):
user = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE)
products = models.ManyToManyField(OrderItem, blank=True)
subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
total = models.DecimalField(default=0.00,max_digits=100,decimal_places=2)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
"""
"""
def product_list_view(request):
queryset = Product.objects.all()
item = OrderItem.objects.all()
cart_obj, new_obj = Cart.objects.new_or_get(request)
print(item)
context = {
'product_list': queryset,
'cart' : cart_obj,
'orderitem' : item
}
return render(request, "products/list.html", context)
"""hmtl page list.hmtl
{% if obj in orderitem %} doesnt print else print allways
"""
{% for obj in product_list %}
<div class='col my-3'>
{{obj.title}}
{{obj.price}}
{{orderitem}}
{% if obj in orderitem %}
<h1>in cart</h1>
{% else %}
<h5>delete</h5>
{% endif %}
</div>
{% endor %}
orderitem = <QuerySet [<OrderItem: iphone 6s>, <OrderItem: hi>]>,
obj = hi ,
in list.hmtl if obj in orderitem always shows error and also tried obj.title in orderitem
But always else statement is printed without any error
trying to check the product is in ordereditem...
Related
I would like to get all items belonging to an invoice and show them to a template without success. What i have done so far is the following:
I have two models:
class Invoice(models.Model):
PAYMENT_OPTIONS = (
('CASH', _('CASH')),
('DEPOSIT', _('DEPOSIT')),
('CARD', _('CARD')),
)
INVOICE_TYPE = (
('Service', _('Service')),
)
invoice_number = models.CharField(max_length=7, unique=True, default='INV4898')
invoice_user = models.ForeignKey(Account, on_delete=models.CASCADE)
invoice_type = models.CharField(max_length=30, choices=INVOICE_TYPE, default='Service')
payment_option = models.CharField(max_length=30, choices=PAYMENT_OPTIONS)
invoice_name = models.CharField(max_length=30, null=True, blank=True)
vat = models.CharField(max_length=9, blank=True, null=True)
gross_amount = models.DecimalField(max_digits=6, decimal_places=2)
vat_amount = models.DecimalField(max_digits=6, decimal_places=2)
net_amount = models.DecimalField(max_digits=6, decimal_places=2)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.invoice_user.first_name} {self.invoice_user.last_name} - {self.invoice_number}"
class Item(models.Model):
invoice = models.ForeignKey(Invoice, related_name='items', on_delete=models.CASCADE)
title = models.CharField(max_length=255)
quantity = models.IntegerField(default=1)
unit_price = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00'))
net_amount = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00'))
vat_rate = models.CharField(max_length=10, default=0)
discount = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00'))
is_paid = models.BooleanField(default=False)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.invoice.invoice_number}"
In the views.py i have a list view like, in which i'm trying to get a list of all invoices based on invoice_number and then match each invoice_number to an invoice in items. However using below code first pring brings all invoice_number(s) and second print brings all items for all invoices, not items per invoice.
def list_invoices(request, userprofile_id):
user_profile = get_object_or_404(Account, pk=userprofile_id)
all_invoices =Invoice.objects.filter(invoice_user=user_profile)
invoice_number = Invoice.objects.values_list('invoice_number')
print(invoice_number)
item_invoice = Item.objects.filter(invoice__invoice_number__in=invoice_number)
print(item_invoice)
context = {
'all_invoices': all_invoices,
'user_profile': user_profile,
'item_invoice': item_invoice,
}
return render(request, 'invoices/list-invoices.html', context)
I would appreciate any help.
You do not need to fetch the Items not the invoice_number of the Invoice. You only need to pass the invoices of the user_profile, and it might be better to also prefetch the Items:
def list_invoices(request, userprofile_id):
user_profile = get_object_or_404(Account, pk=userprofile_id)
all_invoices = Invoice.objects.filter(
invoice_user=user_profile
).prefetch_related('items')
context = {
'all_invoices': all_invoices,
'user_profile': user_profile
}
return render(request, 'invoices/list-invoices.html', context)
then in the template, you can access the .items, so:
<ul>
{% for invoice in all_invoices %}
<li> {{ invoice.invoice_number }}</li>
<ul>
{% for item in invoice.items.all %}
<li>{{ item.quantity }} {{ item.title }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
How to create breadcrumb in my view function?
class Category(MPTTModel):
name = models.CharField(max_length=50, unique=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
slug = models.SlugField( null=True, blank=True)
description = models.TextField(null=True, blank=True)
image = models.ImageField(
upload_to=user_directory_path, default='posts/default.jpg')
def get_absolute_url(self):
return reverse('Category:post_single', args=[self.slug])
class Meta:
ordering = ('-name',)
def __str__(self):
return self.name
class Post(models.Model):
class NewManager(models.Manager):
def get_queryset(self):
return super().get_queryset() .filter(status='published')
options = (
('draft', 'Draft'),
('published', 'Published'),
)
category = TreeForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=250)
excerpt = models.TextField(null=True)
image = models.ImageField(
upload_to='uploads/', default='posts/default.jpg')
image_caption = models.CharField(max_length=100, default='Photo by Blog')
slug = models.SlugField(max_length=250, unique_for_date='publish')
publish = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='blog_posts')
content = models.TextField()
status = models.CharField(
max_length=10, choices=options, default='published')
favourites = models.ManyToManyField(
User, related_name='favourite', default=None, blank=True)
likes = models.ManyToManyField(
User, related_name='like', default=None, blank=True)
like_count = models.BigIntegerField(default='0')
views = models.PositiveIntegerField(default=0)
thumbsup = models.IntegerField(default='0')
thumbsdown = models.IntegerField(default='0')
thumbs = models.ManyToManyField(User, related_name='thumbs', default=None, blank=True)
objects = models.Manager() # default manager
newmanager = NewManager() # custom manager
def get_absolute_url(self):
return reverse('blog:post_single', args=[self.slug])
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
#views
def post_single(request, post):
post = get_object_or_404(Post, slug=post, status='published')
postcat = Post.objects.filter(category=post.category)
fav = bool
if post.favourites.filter(id=request.user.id).exists():
fav = True
allcomments = post.comments.filter(status=True)
page = request.GET.get('page', 1)
paginator = Paginator(allcomments, 10)
try:
comments = paginator.page(page)
except PageNotAnInteger:
comments = paginator.page(1)
except EmptyPage:
comments = paginator.page(paginator.num_pages)
user_comment = None
if request.method == 'POST':
comment_form = NewCommentForm(request.POST)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.post = post
user_comment.save()
return HttpResponseRedirect('/' + post.slug)
else:
comment_form = NewCommentForm()
session_key = 'view_post_{}'.format(post)
if not request.session.get(session_key,False):
post.views +=1
post.save()
request.session[session_key] = True
return render(request, 'blog/single.html', {'post': post,'Category': Category.objects.all(),'Category2': postcat,
'comments': user_comment, 'comments': comments, 'comment_form': comment_form, 'allcomments': allcomments, 'fav': fav})
blog/single.html
{{ node.name }}
I want in my single post info (post_single) breadcrumb with category. Something like this: Category > Subcategory > Sub-Subcategory .,,,
Someone told me to use get_ancestors:
Example:
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">🏠</li>
{% for node in post.category.ancestors %}
<li class="breadcrumb-item">{{node.name}}</li>
{% endfor %}
<li class="breadcrumb-item active" aria-current="page">{{ object }}</li>
</ol>
</nav>
{{ post.category }}
How to implement this with my model?
Thank you. I would be grateful.
Views.py defining the context in view
def customers(request, pk):
customer = Customer.objects.get(id=pk)
issues = customer.issue_set.all()
receives = customer.receive_set.all()
context={'customer':customer,'issues':issues,'receives':receives}
return render(request,'accounts/customers.html')
in html
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer.email}}</p>
<p>Phone: {{customer.phone}}</p>
</div>
</div>
{% for issue in issues %}
<td>{{issue.item}}</td>>
<td>{{issue.item.category}}</td>
<td>{{issue.date_created}}</td>
<td>{{issue.status}}</td>
<td><a href="">UPDATE</td>
<td><a href="">DELETE</td>
{% endfor %}
#Model
class Item(models.Model):
CATEGORY = (
('Gudang Kering', 'Gudang Kering'),
('Gudang Basah','Gudang Basah'),
)
name = models.CharField(max_length=200,null= True)
stock = models.IntegerField(default='0', blank=False, null=True)
category = models.CharField(max_length=200,null= True,choices=CATEGORY)
reorderlevel = models.IntegerField(default='0', blank=False, null=True)
maxreorderlevel = models.IntegerField(default='0', blank=False, null=True)
description = models.CharField(max_length=200,null= True, blank= True)
date_created = models.DateTimeField(auto_now_add= True)
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.name
class Issue(models.Model):
STATUS = (
('Pending', 'Pending'),
('Granted','Granted'),
('Denied','Denied'),
)
customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL)
item = models.ForeignKey(Item, null=True, on_delete= models.SET_NULL)
quantity = models.IntegerField(default='0', blank=False, null=True)
date_created = models.DateTimeField(auto_now_add=True, auto_now=False)
status = models.CharField(max_length=200,null= True, choices=STATUS)
def __str__(self):
return self.status + ' ' +str(self.customer)
I tried to get the object by id of the customer in order to make it a dynamic url where the url will depend on str:pk of customer id
i managed to show output data if i do
customer = Customer.objects.all #but that will show all the customer
so i tried as in the view to get the id
and define it with parent.child_set.all
but it doesn't show up,even the text update and delete don't show up in
Have 2 models
class Category(MPTTModel):
title = models.CharField()
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
class Product(models.Model):
category = models.ForeignKey(Category, blank=True, null=True)
I want to get tree from both models.
Now i can get:
in views
nodes = Category.objects.all()
in template
{% for n in nodes %}
{% for t in n.product_set.all %}
But i want to get
nodes = Category.objects.all().**insert_to_category_product_with_filter**(id__in=[list_id])
I found only one solution via template_tag
#register.filter()
def filter_GET(node, GET):
qs = node.product_set.all().prefetch_related('product_set')
product = GET.get('product', None)
if product:
qs = qs.filter(product_id=product)
any_more = GET.get('any_more', None)
return qs
in template
{% for n in node|filter_GET:request.GET %}
I get this error:
'Searches' object has no attribute 'object'. I am using the generic ListView and I iterate over object_list in template. That is where the error comes in. My view is simple. Just attaching the model. All the relevant code is here.
Thanks
urlpatterns:
urlpatterns = patterns('',
url(r'^create/$','customsearches.views.create_search' , name='create_search'),
url(r'^list/$', SearchListView.as_view(template_name='search_list.html'), name='search_list'),
)
my model:
class Searches(models.Model):
SELLER_CHOICES=(('OWNER','owner'),
('DEALER','dealer'),
('BOTH','both'), )
#search_id = models.IntegerField(primary_key=True)
user = models.ForeignKey(User)
make = models.CharField(max_length=100, blank=True)
model = models.CharField(max_length=100, blank=True)
keywords = models.CharField(max_length=100, blank=True)
max_price = models.IntegerField(blank=True, null=True)
min_price = models.IntegerField(blank=True, null=True)
max_year = models.IntegerField(blank=True, null=True)
min_year = models.IntegerField(blank=True, null=True)
pic_only = models.NullBooleanField()
search_title_only = models.NullBooleanField()
owner_dealer_all = models.CharField(max_length=10,choices=SELLER_CHOICES,verbose_name='owner/dealer')
class Meta:
#managed = False
db_table = 'Searches'
verbose_name_plural = "Searches"
def __unicode__(self):
return "%s %s %s-%s" %(self.make,self.model,self.max_year,self.min_year)
def get_absolute_url(self):
return reverse('postings.views.detail',args=[model_to_dict(self.object)])
view:
class SearchListView(ListView):
model=Searches
template:
{% extends "base.html" %}
{% block content %}
{% for obj in object_list %}
<p>{{ obj }}</p>
{% endfor %}
{% endblock %}
The problem is on the line:
return reverse('postings.views.detail',args=[model_to_dict(self.object)])
Searches model doesn't really have an object attribute.
model_to_dict() needs a model instance:
model_to_dict(self)
Hope that helps.