Render simple two row table in TWIG template - Symfony2 - doctrine-orm

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.

Related

How to Repeat Parts of Jinja2 Template

I realize a couple of similar questions on this have been asked, but they don't relate specifically to what I'm trying to do and I'm pretty much a total beginner, so the answers seem more advanced than what I think I'm expected to do.
I'm working on implementing a Jinja2 template with Python code into an html page of notes I've been keeping while taking this course.
So...
The html block I'm trying to template and repeat has the following structure:
<h1>Stage Number</h1>
<div class = "lesson">
<h2>Lesson Number</h2>
<div class="concept">
<div class="concept-title"> Title </div>
<div class="concept-description">
<p>Description paragraph</p>
<p>Description paragraph</p>
</div>
<div class="concept-title"> Title</div>
<div class="concept-description">
<p>Description paragraph</p>
</div>
</div>
</div>
For each stage, lesson numbers vary and each title has a varying number of description paragraphs.
My code is on Github (this is an edited version): https://github.com/graceehayden/Stage4Udacity-Session-2/blob/master/templates/index.html
My main.py file has the template code, which is supposed to be implemented in the index.html file.
The course just sort of went over the edge on me and re-watching videos or finding other YouTube tutorials on templating isn't helping because a lot of it is more advanced than I seem to be at this point.
Any help or pointers on how to straighten the variables out so they correlate properly with the index.html file would be so appreciated. When I pretend I don't have so many inputs, I am able to make a simple single variable work and show up when I run the app, but with the complexity I have now and need, it isn't functioning.
It looks like you mostly have the right idea with the code so far.
The big thing that is missing is that you need data types that are sequences to extend this to do what you want here.
Each lesson has a list of concepts with an associated description.
concept1 = {
'name' : 'concept1',
'description1' : 'This is the description for concept1!',
}
lesson1 = {
'name' : 'lesson1',
'concepts': [concept1, concept2] #the list here lets us have more than one value
}
Then each Stage is a data structure that contains a list of different lessons.
stage1 = {
'name' : 'stage1',
'lessons': [lesson1, lesson2],
}
Finally you stuff all these different stages into the template_values
template_values = {
'stages' : [stage1, stage2],
}
Then you need the templating to access the nested data:
{% for stage in stages %}
//do things with this particular stage
{% for lesson in stage['lessons'] %}
//do things with this lesson
{% for concept in lesson['concepts'] %}
//do things with individual concepts
{% endfor %}
{% endfor %}
{% endfor %}
Note: haven't tested the template yet, so might have made some mistakes accessing the dictionary.

Querying a single field within a Jinja2 template

I'm working on an application where users can enter work requests, and subsequently go in and search for requests. The issue I'm having is building out the request summary screen. Basically, it lists the results of a search query. The snippet from the template is as such:
{% for req in workrequests %}
{{ req.id }} {{ req.customer }} {{ req.dateEntered }} {{ req.Contact }}
{% endfor %}
Here's wher I get hung up. The req.customer, and req.Contact fields are just keys for the customer and contact databases. I want to display the customer name and contact name. I assume the following queries should do the trick:
Customer.query.filter_by(req.customer).one()
Contact.query.filter_by(req.Contact).one()
Problem is, that will return the entire record. I'm just after the name field from both of those tables to put into my template, which is where the problem is. I'm not sure how to proceed with this
Customer.query is a short form of db.session.query(Customer). Use the latter to query for specific columns:
db.session.query(Customer.name).filter_by(id=req.customer).one()
Although I think that what you really want is a single query that gets all the data at once. Something like:
db.session.query(
WorkRequest.id,
WorkRequest.dateEntered,
Customer.name,
Contact.name
).join(
Customer,
Contact
).filter(...)

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: How do I get the number of elements returned in a database call?

This seems to me like a very simple question, but I can't seem to find the answer.
All I need to do is determine the number of objects returned by a database query.
The specific circumstance is this: I have a model named Student. This model has a ManyToManyField member named courses_current, which relates to a table of Course models. When I pass my Student instance to a template, I want to be able to do something like the following (the syntax may not be exact, but you'll get the basic idea):
<div id="classes">
{% if student.classes_current.all.size == 0 %}
<h1> HEY! YOU AREN'T TAKING ANY CLASSES! REGISTER NOW!
{% else %}
Here are your courses:
<!-- ... -->
{% endif %}
</div>
Now, I'm fairly certain that X_set.all.size is not a real thing. In the manage.py shell I can just use len(student.classes_current.all()), but I don't know of any way to use built-in functions, and "dictionary-like objects" don't have .size() functions, so I'm at a loss. I'm sure there's a very simple solution (or at least I hope there is), but I can't seem to find it.
{{ student.classes_current.all.count }} but be warned that it doesn't fetch the objects so you will need to do a separate query if you want to loop over them.
If you need loop over the classes for tag has way to get what you need.
{% for cl in student.current_classes.all %}
{{ cl }}
{% empty %}
<h1>Hey! ...</h1>
{% endfor %}
Documentation https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#for-empty

Django Custom Template Tag with Context Variable Argument

I have a custom template tag which shows a calendar. I want to populate certain items on the calendar based on a dynamic value.
Here's the tag:
#register.inclusion_tag("website/_calendar.html")
def calendar_table(post):
post=int(post)
imp=IMP.objects.filter(post__pk=post)
if imp:
...do stuff
In my template, it works fine when I pass a hard coded value, such as
{% load inclusion_tags %}
{% calendar_table "6" %}
However when I try something like {% calendar_table "{{post.id}}" %} , it raises a error a ValueError for the int() attempt. How can I get around this?
You want {% calendar_table post.id %}; the extra {{ and }} are what are causing you the heartburn.
Note that, in your custom tag, you need to take the string ("post.id") that gets passed and resolve it against the context using Variable.resolve. There's more information on that in the Django docs; in particular, look here: http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#passing-template-variables-to-the-tag