My cart view.
I have passed context on return but it doesn't appear on the templates. If i print the
def cart(request):
total = 0
quantity = 0
cart_items = None
tax = None
grand_total = None
try:
cart = Cart.objects.get(cart_id=_cart_id(request))
cart_items = CartItem.objects.filter(cart=cart, is_active=True)
for cart_item in cart_items:
total += (cart_item.product.price * cart_item.quality)
quantity = cart_item.quality
tax = (total / 100) * 2
grand_total = total + tax
except:
pass
context = {
'total': total,
'quantity': quantity,
'cart_items': cart_items,
'tax': tax,
'grand_total': grand_total,
}
return render(request, 'c.html', context)
Html Template. Here I created a for loop to get items from the array. But It doesn't show any objects from the array. But always print "Item" string for each object.
{% extends 'base.html' %}
{% load static %}
{% block content %}
{% for item in cart_items %}
<h1>item.product.product_name </h1>
{% endfor %}
{% endblock %}
You code is not correct i think. Try this:
{% extends 'base.html' %}
{% load static %}
{% block content %}
{% for item in cart_items %}
{{item.product.product_name}}
{% endfor %}
{% endblock %}
Related
What I want to do :
Display the human readable value of a charfield with choices via get_F00_display or other in views.py and then in template.
I have a Leave model for leaves management and want to display a template with all the leaves associated with the authenticated user.
What I have done :
Of course, I've read Django documentation (4.1) and find something interesting with get_F00_display but cannot make it works fine.
model.py (simplified)
class Leave(CommonFields):
LEAVES_TYPES = [
('10', _('Type 1')),
('20', _('Type 2')),
('30', _('Type 3')),
]
owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
type = models.CharField(max_length=3, choices=LEAVES_TYPES, null=True, default="10")
def __str__(self):
return self.owner.first_name + " " + self.owner.last_name + " : du " + self.begin_date.strftime("%d-%m-%Y") + " au " + self.end_date.strftime("%d-%m-%Y")
views.py
from django.shortcuts import render
from django.utils.translation import gettext as _
from .models import Leave
from django.views import generic
class LeaveListView(generic.ListView):
model = Leave
context_object_name = 'leave_list'
def get_queryset(self):
return Leave.objects.filter(is_active=True).values('type', 'begin_date','end_date','range','comment','status')
def get_context_data(self, **kwargs):
# Call the base implementation first to get the context
context = super(LeaveListView, self).get_context_data(**kwargs)
# Create any data and add it to the context
context['colHeaders'] = ['Type',
'From',
'To',
'Range',
'Comment',
'Status',]
return context
leave_list.html
{% extends "main/datatables.html" %}
<!-- TABLE TITLE -->
{% block tableTitle %}Leaves{% endblock %}
<!-- TABLE HEADER -->
{% block tableHeader %}
{% if colHeaders %}
{% for header in colHeaders %}
<th>{{header}}</th>
{% endfor %}
{% else %}
<p>No results</p>
{% endif %}
{% endblock %}
<!-- TABLE BODY -->
{% block tableBody %}
{% if leave_list %}
{% for leave in leave_list %}
<tr>
<td>{{leave.type}}</td>
<td>{{leave.begin_date}}</td>
<td>{{leave.end_date}}</td>
<td>{{leave.range}}</td>
<td>{{leave.comment}}</td>
<td>{{leave.status}}</td>
</tr>
{% endfor %}
{% else %}
<p>No results</p>
{% endif %}
{% endblock %}
<!-- TABLE FOOTER -->
{% block tableFooter %}
{% if colHeaders %}
{% for header in colHeaders %}
<th>{{header}}</th>
{% endfor %}
{% else %}
<p>No results</p>
{% endif %}
{% endblock %}
Problem :
{{leave.type}}
returns the key of the choices but I'm trying to display the human readable name in LEAVES_TYPES like "Type 1"...
What I've tried :
Using get_F00_display this way : get_type_display in my views.py :
def get_queryset(self):
return Leave.objects.filter(is_active=True).values(get_type_display, 'begin_date','end_date','range','comment','status')
Same thing in the template but no readable name displayed...
Hey guys I made a model that can upload some files and then i made two views upload_list.html and upload_detail.html the list pages contains the links to the actual detail page but while clicking on the links it takes me to the same page again
Here,s the models.py
class Upload(models.Model):
image = models.ImageField(upload_to = 'images',)
file = models.FileField(upload_to = 'images/%Y/%M/%d/')
name = models.CharField(max_length = 200)
def __str__(self):
return self.name
def get_absolute_url(self):
return self.pk{}
Here,s the views.py
def upload_list(request):
upload_list = Upload.objects.all()
return render(request,'app/upload_list.html',{'upload_list':upload_list})
def upload_detail(request,pk):
upload_detail = get_object_or_404(Upload,pk = pk)
return render(request,'app/upload_detail.html',{'upload_detail':upload_detail})
Hers, the urls.py
url(r'^upload/',views.upload_list,name = 'upload_list'),
url(r'^upload/(?P<pk>[-\w]+)/$',views.upload_detail,name = 'upload_detail'),
Hers, the upload_list.html
{% extends 'app/base.html' %}
{% block content %}
{% load static %}
{% for i in upload_list %}
<div class="jumbotron">
{{i.name}}
<br>
</div>
{% endfor %}
{% include 'app/index_js.html' %}
{% endblock content %}
Here,s the upload_Detail.html
{% extends 'app/base.html' %}
{% block content %}
{% load static %}
<div class="jumbotron">
<h1>{{upload_detail.name}}</h1>
<img src="{{upload_detail.name}}" alt="'Image for you,r betterment "></img>
{{upload_detail.file}}
</div>
{% include 'app/index_js.html' %}
{% endblock conten`t %}`
Have you tried put your urls.py like this ?
url(r'^upload/$',views.upload_list,name = 'upload_list'),
url(r'^upload/(?P<pk>[-\w]+)/$',views.upload_detail,name = 'upload_detail'),
or
url(r'^upload/(?P<pk>[-\w]+)/$',views.upload_detail,name = 'upload_detail'),
url(r'^upload/$',views.upload_list,name = 'upload_list'),
The $ is a regex that indicates a end of string.
I hope that helps you
Code
engine.py ==>
class YearGroupCount():
def __init__(self, year, count, months):
self.year = year
self.count = count
self.months = months
class MonthGroupCount():
def __init__(self, month, count):
self.month = month
self.month_name = calendar.month_name[month]
self.count = count
class BlogCountsEngine():
def __init__(self):
self.year_group_counts = {}
def _add_date(self, year, month):
if str(year) in self.year_group_counts:
year_obj = self.year_group_counts[str(year)]
else:
year_obj = YearGroupCount(year, 0, {})
year_obj.count += 1
if str(month) in year_obj.months:
month_obj = year_obj.months[str(month)]
else:
month_obj = MonthGroupCount(month, 0)
month_obj.count += 1
year_obj.months[str(month)] = month_obj
self.year_group_counts[str(year)] = year_obj
def get_calculated_blog_count_list(self):
if not Blog.objects.count():
retval = {}
else:
for blog in Blog.objects.all().order_by('-posted'):
self._add_date(blog.posted.year, blog.posted.month)
retval = self.year_group_counts
return retval
views.py ==>
def outer_cover(request):
archives = BlogCountsEngine().get_calculated_blog_count_list()
retdict = {
'categories': Category.objects.all(),
'posts': posts,
'archives': archives,
}
return render_to_response('blog/blog_list.html', retdict, context_instance=RequestContext(request))
template html ==>
<div class="well">
<h4>Arşivler</h4>
<ul>
{% if archives %}
{% for y_key, yr in archives %}
<li>{{ yr.year }} ({{ yr.count }})</li>
{% for m_key,mth in yr.months %}
<li> - {{ mth.month_name }} ({{ mth.count }})</li>
{% endfor %}
{% endfor %}
{% endif %}
</ul>
</div>
Question:
I am building my own blog with django. I want to iterate in archives to show them in main page but i cannot reach instances' attributes in dictionary
When i run the code over in here the result html is ==>
<div class="well">
<h4>Arşivler</h4>
<ul>
<li> ()</li>
</ul>
</div>
What am i missing or doing wrong?
You can use dict.items method. In python 2.x better use dict.iteritems instead.
{% for y_key, yr in archives.items %}
<li>{{ yr.year }} ({{ yr.count }})</li>
{% for m_key, mth in yr.months.items %}
<li> - {{ mth.month_name }} ({{ mth.count }})</li>
{% endfor %}
{% endfor %}
I'm trying to create some graphics in my template with data from my models. I'm doing a survey app. Each survey has some questions, and each question has some answers. The user answer each question. So I count the answer for each question. I want to plot these answers in my template.
I'm using this view to count the data and render to template:
def SurveyResults(request, id):
user = request.user
if user.is_authenticated():
quest_survey = Survey.objects.get(id=2)
quests = quest_survey.questions()
graphic = {}
graphic_id = 1
if quests:
for quest in quests:
a1 = AnswerSelect.objects.filter(question_id=quest.id, body = "answer 1").count()
a2 = AnswerSelect.objects.filter(question_id=quest.id, body = "answer 2").count()
a3 = AnswerSelect.objects.filter(question_id=quest.id, body = "answer 3").count()
a4 = AnswerSelect.objects.filter(question_id=quest.id, body = "answer 4").count()
graphic[str(graphic_id)] = [['answer1', a1], ['answer2', a2], ['answer3', a3], ['answer4', a4] ]
graphic_id += 1
return render(request, 'results.html', locals())
else:
msg = "A Survey não possui questões"
return HttpResponseRedirect('profile.html')
else:
msg = "Usuario ou senha digitados incorretamente"
return HttpResponseRedirect('home.html', {'msg': msg})
The question is, how can I get the values of graphic["1"],...,graphic["n"] in my template?
I'm trying to do this:
{% if graphic %}
{% for g in graphic %}
{% for item in g %}
{{ item }}
{% endfor %}
{% endfor %}
{% endif %}
But instead of the data, I only get the value of the ids: 1,2,...,n
Use items function to display the keys and values of the dictionary in template:
{% for key, value in graphic.items %}
{% for item in value %}
{{ item }}
{% endfor %}
{% endfor %}
I'm having some trouble using get_absolute_url in a template. It seems to work fine if I just pass in one of my store objects and say {{ store.get_absolute_url }}, but if I have to iterate through a dictionary of stores and then use the get_absolute_url function, it returns nothing. Exactly what I'm doing is below:
class Store(EthicalObject):
type = "Store"
name = models.CharField(max_length=50)
company = models.ForeignKey(Company, verbose_name="Company", null=True, blank=True)
location = models.OneToOneField(Location, verbose_name="Location", null=True, blank=True)
products = models.ManyToManyField('Product', related_name="%(class)s_related", db_table=u'ethicsdb_products_to_stores', blank=True)
companies = models.ManyToManyField('Company', related_name="%(class)s_related", db_table=u'ethicsdb_companies_to_stores', blank=True)
def get_absolute_url(self):
return ('store_details', [str(self.id)])
get_absolute_url = models.permalink(get_absolute_url)
This works:
views.py:
def fetch_sidebar_data(shop_object):
sidebar_modules = {}
if shop_object.content_type.name == 'company':
sidebar_modules['related_stores'] = shop_object.stores.all()
sidebar_modules['related_products'] = shop_object.products.all()
if shop_object.content_type.name == 'store':
sidebar_modules['related_companies'] = shop_object.companies.all()
sidebar_modules['related_products'] = shop_object.products.all()
if shop_object.content_type.name == 'product':
sidebar_modules['related_stores'] = shop_object.stores.all()
sidebar_modules['related_companies'] = shop_object.companies.all()
sidebar_modules['tags'] = shop_object.tags
return sidebar_modules['related_stores'][1]
def company_details(request, company_id):
company = get_object_or_404(Company, id=company_id)
sidebar_modules = fetch_sidebar_data(company)
return render_to_response('company/details.html', {'company': company, 'sidebar_modules': sidebar_modules}, context_instance=RequestContext(request))
template:
{% extends "base-onecol.html" %}
{% block page_div_extra_attr %}class="twocol"{% endblock %}
{% block sidebar_content %}
<div id="sidebar-right">
<h1>{{ sidebar_modules.name }}{{sidebar_modules.get_absolute_url }}</h1>
</div>
{% endblock %}
This doesn't work:
views.py:
def fetch_sidebar_data(shop_object):
sidebar_modules = {}
if shop_object.content_type.name == 'company':
sidebar_modules['related_stores'] = shop_object.stores.all()
sidebar_modules['related_products'] = shop_object.products.all()
if shop_object.content_type.name == 'store':
sidebar_modules['related_companies'] = shop_object.companies.all()
sidebar_modules['related_products'] = shop_object.products.all()
if shop_object.content_type.name == 'product':
sidebar_modules['related_stores'] = shop_object.stores.all()
sidebar_modules['related_companies'] = shop_object.companies.all()
sidebar_modules['tags'] = shop_object.tags
return sidebar_modules
template:
{% extends "base-onecol.html" %}
{% block page_div_extra_attr %}class="twocol"{% endblock %}
{% block sidebar_content %}
<div id="sidebar-right">
{% for module_name,module in sidebar_modules.items %}
{% ifequal module_name "related_stores" %}
<h3>Sold Here</h3>
{% for related_store in module.values %}
{{ related_store.name }}<br/>
{% endfor %}
{% endifequal %}
{% ifequal module_name "related_products" %}
<h3>Buy Local</h3>
{{ module }}<br/>
{% endifequal %}
{% ifequal module_name "related_companies" %}
<h3>
{{ module }}<br/>
{% endifequal %}
{% ifequal module_name "tags" %}
{{ module }}<br/>
{% endifequal %}
{% endfor %}
</div>
{% endblock %}
In the second one, I just get no return from get_absolute_url. I know it's working in other places when I print it out. Is this a Django bug, the inability to use get_absolute_url in a dictionary of dictionaries?
Wow, that was a rather convoluted question.
Your problem is here: {% for related_store in module.values %}
module is a QuerySet. .values is calling the QuerySet method which returns a dictionary containing the field values for each row. A dictionary has no get_absolute_url attribute, and get_absolute_url isn't a field in the model.
Just use {% for related_store in module %} and you'll be dealing with actual model instances rather than dictionaries, which means {{ related_store.get_absolute_url }} will work fine.