How can I access items within a ndb query object clientside? - django

I'm working with appengine, django and webapp2 and am sending a query object clientside such that
{{ exercise_steps }}
returns
Query(kind='ExStep')
and
{{ exercise_steps.count }}
returns 4
I'm trying to chuck the variable exercise_steps into some javascript code and need to iterate through the items in a javascript (not a django) loop but I cannot seem to access the items.
I've tried {{ exercise_steps|0 }}, {{ exercise_steps[0] }}, {{ exercise_steps.0 }} but it returns nothing. I know I can do this with a django loop but is there a way I can access the objects within the query with a javascript loop using something like
for (var i = 0; i < {{exercise_steps.count}}; i++) {
console.log({{ exercise_steps.i.location }})
}

You can't mix client side code and template code... by the time the javascript runs, your python code is already executed. You are not sending a python object to the javascript - it's executed when the HTML is generated.
You need to recreate array in JS, or have an ajax call return an array from python.
var steps = [
{% for step in exercise_steps %}
{{ step.location }}{% if not forloop.last %},{% endif %}
{% endfor %}]; // now your python iterable is a JS array.

Related

Django custom template filter feeding cookie or default value

I'm designing a custom django filter, just to make sure it works I have something like this
{{ "Sleeps:"|translate:"fr" }}
and it works.
Now in the final implementation, I want it to get a cookie or else use a default value
{{ pg.title|translate:request.COOKIES.lang|default:"en" }}
I'm getting this error
VariableDoesNotExist at /chalet/belle-chery
Failed lookup for key [lang] in {'_ga': 'GA1.1.1026479868.1547798010', 'cookie-policy': 'true', 'csrftoken': 'VrVrvgZUfFrWhFDFjLIvZgOus9NrmjDx1JwNP2lzvz2FRAGmC1lLrKwiH4g31X5F', 'sessionid': 'ptp6smvt9w95qtqlkc7klx736u5k7uu5'}
so it doesn't implement the default part.
So I figure there's either a way to fix this or use middleware to set the cookie if it's not set.
Would be nice if it doesn't need middleware.
so it doesn't implement the default part.
It does, it applies the |default:"en" filter to the result of {{ pg.title|translate:request.COOKIES.lang }}, not to the request.COOKIES.lang expression.
The easiest way to solve this is probably defining a local variable, for example with the {% with ... %} template tag:
{% with lang=request.COOKIES.lang|default:"en" %}
{{ pg.title|translate:lang }}
{% endwith %}

{{ }} is not getting parsed by pyjade as expected with django

I have line of pyjade
a.js-track(data-track-data="{\"Job ID\":\"{{ job_details|get_or_na:'id' }}\",\"Job Title\":\"{{ job_details|get_or_na:'title' }}\",\"Company Name\":\"{{ job_details|get_or_na:'organization'|get_or_na:'name' }}\"}", data-track-dynamic-attrs="[\"Stakeholder\"]",href="{% url 'job_detail' job_details.title|slugify job_details.id %}")
which is being rendered as
<a href="/job/operations-manager/b1ac846e-6834-40c4-8bcf-122c093820b1/" data-track-data="{"Job ID":"{{ job_details|get_or_na:'id' }}","Job Title":"{{ job_details|get_or_na:'title' }}","Company Name":"{{ job_details|get_or_na:'organization'|get_or_na:'name' }}"}" data-track-dynamic-attrs="["Stakeholder"]" class="js-track">
I expect it to {{ }} being replaced by intended values rather than being rendered with html.
I am using 4.0.0 version of pyjade here as templating language.
Try to use #{value}
And for the conditions try to create a variable before the line so you can have more control
- var condition = inline_condition
p= condition

Render simple two row table in TWIG template - Symfony2

This question is terrible basic, but I tried to find out the answer both on the Symfony documentation as well as in forums and tutorials but everyone does it differently and no solution seems to work with my code.
I just need to render two columns of data with a TWIG template. It has to show the messages sent from a contact form where the only fields are the email of the sender and the body of the message.
The Entity for this is named as Enquiry.
The member function is as follows:
public function showAction()
{
$enquiry = $this->getDoctrine()->getRepository('MyWebSiteBundle:Enquiry')->findAll()
if (!$enquiry) {
throw $this->createNotFoundException(
'No elements found'
);
}
return $this->render('MyWebSiteBundle:Page:admin.html.twig', array('object' => $enquiry));
}
And the part to the template which is supposed to show the result looks as follows:
{% for item in object %}
{{ item.email }} - {{ item.body }} <br>
{% else %}
<h2>Aoutch ! No data !</h2>
{% endfor %}
Thank you very much in advance I will be much relieve to find the answer to this.

Django ManyToMany two for loops

I have two for loops from which the first one (for i in var) is for getting the posts and the other is for getting the tags (ManyToManyField in the Post model) for that post:
{% for i in var %}
{% for j in i.tags.all %}
{{ j.name }}
{% endfor %}
{% endfor %}
Why won't this work?
EDIT:
Here is what the variables contain:
var:
[<SearchResult: myapp.post (pk='1')>, <SearchResult: myapp.post (pk='2')>]
and here is {{ i.tags }}:
<django.db.models.fields.related.ManyRelatedManager object at 0x1620dd0>
If I try to iterate it with .all it returns nothing.
EDIT 2:
This might be the problem - var is a variable from a SearchQuerySet (django haystack):
var = SearchQuerySet().all()
Inside the template, the j is something like <SearchResult: myapp.post (pk='1')>, which does not have .tags attributes. Try for j in i.object.tags.all, the .object refers the actual Model instance.
Note that Django normally does not complain about trying of accessing non-existing attributes (i.tags here) during template rendering. Hence rendering nothing may also mean incorrect attributes referring.
Solved it by adding the tag field into the haystack searchindex. Now it outputs the list of tags. Thank you all for your help!

Django - use template tag and 'with'?

I have a custom template tag:
def uploads_for_user(user):
uploads = Uploads.objects.filter(uploaded_by=user, problem_upload=False)
num_uploads = uploads.count()
return num_uploads
and I'd like to do something like this, so I can pluralize properly:
{% with uploads_for_user leader as upload_count %}
{{ upload_count }} upload{{ upload_count|pluralize }}
{% endwith %}
However, uploads_for_user leader doesn't work in this context, because the 'with' tag expects a single value - Django returns:
TemplateSyntaxError at /upload/
u'with' expected format is 'value as name'
Any idea how I can get round this?
You could turn it into a filter:
{% with user|uploads_for as upload_count %}
While a filter would still work, the current answer to this question would be to use assignment tags, introduced in Django 1.4.
So the solution would be very similar to your original attempt:
{% uploads_for_user leader as upload_count %}
{{ upload_count }} upload{{ upload_count|pluralize }}
Update: As per the docs assignment tags are deprecated since Django 1.9 (simple_tag can now store results in a template variable and should be used instead)
In Django 1.9 django.template.Library.assignment_tag() is depricated:
simple_tag can now store results in a template variable and should be used instead.
So, now simple tag we can use like a:
It’s possible to store the tag results in a template variable rather
than directly outputting it. This is done by using the as argument
followed by the variable name. Doing so enables you to output the
content yourself where you see fit:
{% get_current_time "%Y-%m-%d %I:%M %p" as the_time %}
<p>The time is {{ the_time }}.</p>