Django render Dictionary - python

Why cant i acsess the dict that i am making here:
def kalkuler(request):
fotlister = Produkt.objects.filter(under_kategori__navn__iexact="lister")
kalkuler = ProduktKalkureing.objects.all()
beregning = {}
if request.method == "POST":
omkrets = request.POST['omkrets']
print(omkrets)
for i in kalkuler:
kalk = math.ceil((int(omkrets)/i.lengde)*1000)
add = ({'produkt_tittel': i.produkt.produkt_tittel,
'produkt_bilde': i.produkt.produkt_bilde,
'produkt_info': i.produkt.produkt_info,
'produkt_link': i.produkt.produkt_link,
'pris_heltall': i.produkt.pris_heltall,
'antall_kalk': kalk,
'total_kost': kalk * i.produkt.pris_heltall
})
beregning.update(add)
print(beregning)
context = {'kalkuler': kalkuler, 'beregning': beregning}
return render(request, 'frontend/kalkuler/fotlist_kalkuler.html', context)
With the standard django code?
{% for b in beregning %}
{{b.produkt_bilde}}
{% endfor %}
Also when i make the dictionary it only adds the last value. How do i make it so it adds every value.

For what you seem to achieve, you need a list instead of a dict
def kalkuler(request):
...
beregning = []
...
beregning.append(add)
...

Related

Passing list dict to template not working django

I am trying to pass a list called eligable so that I can display on my website but when I run my website it does not display the list. I do not understand what is wrong.
code:
def specificDate(response):
empName = employeeName.objects.all()
eligable = []
if 'checkEmployee' in response.POST:
n = response.POST.get("nameEmployee")
specDate = response.POST.get("date")
if employeeName.objects.filter(employee=n).exists() and Name.objects.filter(date=specDate).exists():
emp = employeeName.objects.get(employee=n)
t = Name.objects.get(name=emp, date=specDate)
overT = Name.objects.filter(name=emp, overtime=True)
for item in overT:
eligable.append(item.date)
checkIn = t.timeIn.strftime("%H:%M:%S")
checkOut = t.timeOut.strftime("%H:%M:%S")
datee = datetime.strptime(specDate,'%Y-%m-%d')
print("Here:: ",t.date)
print("Month:: ",datee.month)
messages.info(response, checkIn + ' - ' + checkOut)
return redirect('/specificDate')
else:
messages.info(response, 'Name does not exist')
else:
pass
return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable})
This is the html to print my list:
{% for item in eligable %}
<div class="pad3">
{{item}}
</div>
{% endfor %}
There are two return statements in your code:
return redirect('/specificDate')
and
return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable})
The first one is just redirecting without populating context.
The second one does populate context but is reached only when eligable is empty.
I think changing the first return to the second one should solve it.
edit: and you are missing {% endfor %} here. But it should give you an error if you miss it in your complete code.

django custom template filter with variable as argument

I'm using a Django custom template filter as described here to access entries in a 3D array in my template. I pass the 3D array swipeData from views.py to index.html.
index.html:
function getNearestHalfHourTimeString() {
var now = new Date();
var hour = now.getHours();
var minutes = now.getMinutes();
var ampm = "AM";
if (minutes < 15) {
minutes = "00";
} else if (minutes < 45){
minutes = "30";
} else {
minutes = "00";
++hour;
}
return("T" + hour + minutes);
}
var currentDay = (new Date()).getDay();
var currentTimeRounded = getNearestHalfHourTimeString();
{% block content %}
{% load hello_extras %}
var atrium = {{swipeData|bldIndex:'ATRIUMCAFE'|dayIndex:currentDay|timeIndex:currentTimeRounded }};
{% endblock %}
hello_extras.py:
from django import template
register = template.Library()
#register.filter
def bldIndex(List, strIndex):
dctBuild = {'ATRIUMCAFE':0, 'BUTLERCOLLEGE':1, 'CAFEVIVIAN':2, 'CENTERFORJEWISHLIFE':3, 'CHANCELLORGREEN':4, 'CHEMISTRYCAFE':5, 'CONCESSIONS_12':6, 'FORBESCOLLEGE':7, 'FRISTCSTORE':8, 'FRISTGALLERY1':9, 'FRISTGALLERY2':10, 'FRISTGALLERY3':11, 'FRISTGALLERY4':12, 'FRISTWITHERSPOONS':13, 'GRADUATECOLLEGE':14, 'LIBRARY_CART':15, 'MATHEYCOLLEGE':16, 'ROCKEFELLERCOLLEGE':17, 'STUDIO34BUTLEREMPORIUM':18, 'WHITMANCOLLEGE':19, 'WILSONCOLLEGE':20, 'WOODROWWILSONCAFE':21, 'FIRESTONELIBRARY':22}
i = int(dctBuild.get(strIndex))
return List[i]
#register.filter
def dayIndex(List, strIndex):
return List[int(strIndex)]
#register.filter
def timeIndex(List, strIndex):
dctTime = { "T0000":0, "T0030":1, "T0100":2, "T0130":3, "T0200":4, "T0230":5, "T0300":6, "T0330":7, "T0400":8, "T0430":9, "T0500":10, "T0530":11, "T0600":12, "T0630":13, "T0700":14, "T0730":15, "T0800":16, "T0830":17, "T0900":18, "T0930":19, "T1000":20, "T1030":21, "T1100":22, "T1130":23, "T1200":24, "T1230":25, "T1300":26, "T1330":27, "T1400":28, "T1430":29, "T1500":30, "T1530":31, "T1600":32, "T1630":33, "T1700":34, "T1730":35, "T1800":36, "T1830":37, "T1900":38, "T1930":39, "T2000":40, "T2030":41, "T2100":42, "T2130":43, "T2200":44, "T2230":45, "T2300":46, "T2330":47}
i = int(dctTime.get(strIndex))
return List[i]
I get the error
VariableDoesNotExist at /
Failed lookup for key [currentDay] in u"[{
How can I use a variable as an argument to my custom template filter? I've tried using a with block already.
Your problem is that you are trying to pass a JS var to a django filter, that it's wrong
currentDay and currentTimeRounded are JS Vars not Python vars, for this reason filter fails
Remember that you can get all necessary info in your view, and then render in your template
I suggest you that format your data in your view and in the template assign it to the respective JS var
some as follow
def some_view(request):
# here you can calculate, convert, create all values to your chart as you need
# if you need time or date can use datetime module ie
values_to_chart = ""
render(request, template_name, locals())
And in your template
var atrium = {{values_to_chart}}

Django Formsets: How to properly iterate over forms in a formset and save the corresponding dictionaries

I have created a formset and I know that form data is being returned as a dictionary. I thought that I could just loop over the forms in a formset and store every dictionary in another dictionary. That doesn't seem to work though, because I am only able to store the latest form (in my template I can dynamically add and remove forms). What I tried was this:
def index(request):
data = {}
data['education_data'] = {}
EducationFormSet = formset_factory(EducationForm)
if request.method == "POST":
persoform = PersonalForm(request.POST)
education_formset = EducationFormSet(request.POST)
if persoform.is_valid() and education_formset.is_valid():
data['personal_data'] = persoform.cleaned_data
entry = 1
en = 'entry_%d' % entry
for form in education_formset:
data['education_data'][en] = form.cleaned_data
entry = entry + 1
print(data)
My wanted output would be:
data = {'personal_data':{inputs}, 'education_data': { 'entry_1':{inputs}, ... 'entry_n':{inputs}}}
EDIT:
The problem was the way I tried to add keys to the "Education_Data" key. The following works:
for form in education_formset:
data['education_data']['entry_%d' % entry] = form.cleaned_data
[...]

Jinja2 Extension Tag within another Tag

I'm tring to do something like this
{% mytag country "italy" year "2014" %}
workday
{% holyday %}
not workday
{% endmytag %}
But the holyday tag is optional.
This must work too:
{% mytag country "italy" year "2014" %}
workday
{% endmytag %}
I wrote the code
class MytagExtension(Extension):
tags = set(['mytag'])
def __init__(self, environment):
super(TranslateExtension, self).__init__(environment)
def parse(self, parser):
lineno = parser.stream.next().lineno
if parser.stream.skip_if('name:country'):
country= parser.parse_primary()
else:
country= nodes.Const(None)
if parser.stream.skip_if('name:year'):
year = parser.parse_primary()
else:
year = nodes.Const(None)
args = [country, year]
# body1 = parser.parse_statements(['name:holyday']) # not working :)
body = parser.parse_statements(['name:endmytag'], drop_needle=True)
return nodes.CallBlock(self.call_method('_helper', args),
[], [], body).set_lineno(lineno)
def _helper(self, country, year, caller):
etc ....
Is similar to a if else endif, but i didn't find the source code of the if tag (if it exists as Extension)
How can i do this?
Obviously in my _helper I need both the first and second branch because is there that I choose which one to show.
ok, here is an answer, it's not perfect and probably not the best, but it's something.
...
body = parser.parse_statements(
['name:endmytag', 'name:holyday'],
drop_needle=True
)
if not parser.stream.current.test('block_end'):
body.extend ( parser.parse_statements(['name:endmytag'], drop_needle=True) )
args = [
country,
year,
nodes.Const([y.data for x in body for y in x.nodes]), #I don't like this line a lot :)
]
return nodes.CallBlock(self.call_method('_helper', args),
[], [], body).set_lineno(lineno)
...
In this way in the _helper you will receive the third parameter (a list) and choose if return the first or the second element of this list.

Sortable tables in Django

I read some of the other posts about this and some recommendations involved javascript and using other libraries. I did something quick by hand, but I'm new to Django and Python for that matter so I'm curious if this isn't a good way to do it.
HTML
<table>
<tr>
<td>To</td>
<td>Date</td>
<td>Type</td>
</tr>
{% for record in records %}
<tr><td>{{record.to}}</td><td>{{record.date}}</td><td>{{record.type}}</td></tr>
{% endfor %}
</table>
View
headers = {'to':'asc',
'date':'asc',
'type':'asc',}
def table_view(request):
sort = request.GET.get('sort')
if sort is not None:
if headers[sort] == "des":
records = Record.objects.all().order_by(sort).reverse()
headers[sort] = "asc"
else:
records = Record.objects.all().order_by(sort)
headers[sort] = "des"
else:
records = Record.objects.all()
return render_to_response("table.html",{'user':request.user,'profile':request.user.get_profile(),'records':records})
Looks good to me. I'd suggest one minor refactoring in the view code:
headers = {'to':'asc',
'date':'asc',
'type':'asc',}
def table_view(request):
sort = request.GET.get('sort')
records = Record.objects.all()
if sort is not None:
records = records.order_by(sort)
if headers[sort] == "des":
records = records.reverse()
headers[sort] = "asc"
else:
headers[sort] = "des"
return render_to_response(...)
My first port of call for sortable tables is usually sorttable.js ( http://www.kryogenix.org/code/browser/sorttable/ )
or sortable-table ( http://yoast.com/articles/sortable-table/ )

Categories