This may be a simple one. But I could not reason it out. I am using Django 1.7.2
I have a model where there is only one row of data in the table.
Case 1 : objects.all()
info = ModelName.objects.all()
I get the data but when I try to put it in a template, it is not getting displayed.
{% for item in info %}
{{ item.name }}
{% endfor %}
Case 2 : objects.get()
info = ModelName.objects.get()
I get the data and it is getting displayed in template.
{{ info.name }}
Questions:
Could anyone explain why case 1 is not working?
And in case 2 using get() without any pk value is fine?
Case 2 works fine, because the arguments for the get() function are optional. If you don't provide anything, it will match against every record. Since you table only has one, it raises no exception.
See the docs: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#get
Your case 1 should be working, though. Check if your info is in your context for the template.
Related
I'm struggling to get my templatetag to work. I believe it's the syntax or the way i'm calling app_filters. Forgive me i'm learning web application development so if my logic is off please correct me. My goal is to pass a collection of check boxes on one template to a new one filtered at a different level report_id is the collection of each check box.
I have an array in my view from my GET.getlist call below
checkedlist = request.GET.getlist('report_id')
reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)
print (checkedlist)
print (reportlist)
args = {'retreivecheckbox': checkedlist}
return render(request,'accounts/requestaccess.html', args)
When I print my array the console displays it correctly, this example is if there was two check boxes selected:
['88', '89']
<QuerySet ['Common Data Model Reconciliation Load', 'LEJR BPCI IV - ICS Baseline']>
I've created the following templatetag called app_filters defined as:
from django import template
register = template.Library()
#register.filter
def get_list(querydict, itemToGet ):
return querydict.getlist(itemToGet)
Now i'm trying to get my template to display what's in my console but as individual rows/indexes dependent upon user selections. I'm told get_list will do that for me. I've also tried get_at_index. I.E. I want to see retreivecheckbox as
88
89
and not [88,89]
Using the following template my app prints correctly, however, all on one row as 88 89.
{% for app in retreivecheckbox %}
{{ app }}
{% endfor %}
When I try several variations of the following my template displays nothing. Why doesn't my get_list break my array into indexed lines?
{% load app_filters %}
{% for app in retreivecheckbox|get_list:report_id %}
{{ app }}
{% endfor %}
My book example shows it as
{% for app in retreivecheckbox|get_list:"report_id" %}
However, when I use double or single quotes it gives me the following error:
'QuerySet' object has no attribute 'getlist'
Using {{ request.GET|get_list:"report_id" }} prints the list out as [88,89] [88,89]
I've tried all sorts of different variations, but its not displaying as I want it to or it won't display. I've been trying print '\n'.join(map(str, list_of_ints)), it works except the 4 items is still one check box, instead of 4.
Thanks to Daniel for his clarification, this was easily solved by using list tags in HTML. I was over thinking the problem.
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(...)
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!
I'm running a query to get the 5 latest News items. In my template, I want to display the first item in one location, then the remaining 4 further down the page.
In my template, I do something like this:
{% for n in news|slice:":1" %}
{{ n.headline }}
{% endfor %}
... more HTML ...
{% for n in news|slice:"1:" %}
{{ n.headline }}
{% endfor %}
When I look in the Debug Toolbar, this results in two queries to the database: one with LIMIT 1 and another with LIMIT 4 OFFSET 1, but otherwise the same. I appreciate this is Django's way of intelligently only requesting the stuff you actually use, but in this case it seems a little excessive. What's the best way to do this kind of thing?
Convert to a sequence in the view, then slice the sequence.
var = list(somequery[:5])
You just need to force the queryset to evaluate itself before the slice. This could be done as simply as calling len() on it in your view before passing it off to the context.
The Django docs have a complete list of everything that causes a queryset to evaluate. Just do something from that list and you're good.
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