print out django request.META in a template - django

I am trying to print out the values inside the request.META in a template but I cannot get it right. All I got is an error Could not parse the remainder: '[i]' from 'REQ_META[i]'
below is my code:
in my views.py
def index (request):
template = loader.get_template('app/index.html')
page_data = { 'REQ_META': request.META}
context = RequestContext(request, page_data)
return HttpResponse(template.render(context))
in index.html
{% for i in REQ_META %}
{{ i }} = {{ REQ_META[i] }} <br />
{% endfor %}

Well, the right way to inspect the request.META objects would be using pdb in the view, or using tools like django-debugtoolbar.
In my opinion, django debug toolbar is an extremely handy tools for debugging purposes.
Regardless, Your issue is, REQ_META is a dictionary, and the way to parse the elements of the dictionary is:
{% for k, v in REQ_META %}
{{ k }} = {{ v }} <br />
{% endfor %}
Documentation here

There is already an answer, but thought it could be useful for future use:
You just need to access the object like this {{ REQ_META.i }} instead of {{ REQ_META[i] }}
Another option is to use django pprint template filter
{{ REQ_META|pprint }}
Which will always print nicely dict objects (and any other python object)

Related

Get formset name variables in django templates

I am sending a formset to my template. I want to add some style to it, so I need to access his variables.
I took the following code from documentation, where they print the form and it has some attributes, amongside them the name="form-0-title".
for form in formset:
print(form.as_table())
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Django is now open source" id="id_form-0-title"></td></tr>
...
As I want to style my forms, I need to give the inputs a name to know how to treat them in the backend. When I do the following in the templates
{{ proficiency_form.management_form }}
{% for form in proficiency_form %}
{{form.title.name}}
{% endfor %}
I get title, title, ... instead of id_form-0-title, id_form-1-title, ...
How can I get the correct name in the templates?
You can easily get the input's name of your fields like so:
{{ proficiency_form.management_form }}
{% for form in proficiency_form %}
{{form.title.html_name}}
{% endfor %}
If you want to get the label's id, you can consider this approach:
{{ proficiency_form.management_form }}
{% for form in proficiency_form %}
{{form.title.id_for_label}}
{% endfor %}
Read more about it in the official Docs.
You can find a similar(almost duplicate) question here.

Checking for widget attribute in Django templates

I'd need to pass some data from my manually generated form to the template, and would need to check the presence of that information there.
I'm generating my form as such (in the __init__ part):
for i in days_in_month:
self.fields["info_%s" % i] = forms.ChoiceField(label="%s" % i.strftime("%a %d-%m-%Y"),
required=False,
choices=Information._meta.get_field('info').choices,
widget=forms.Select(attrs={'something': 'test'}))
What I would like to do, is to check in the template whether the attribute something is set, and if so, display its value (in the example above: test).
Any idea?
I tried with {{ field.attribute }} as per Access form field attributes in templated Django and the below:
{% for field in form %}
{{ field.label_tag }} {{ field }}
{{ field.widget.attrs.something }}
{% endfor %}
... but that doesn't work (invalid).
Ultimately I want to do something similar to:
{% if field.widget.attrs.something %}{{ field.widget.attrs.something }}{% endif %}
That would be
{{ field.field.widget.attrs.something }}

Access tuple through index value in django template

How do I access the value of tuple through indexing in a template? When i try to do this....django gives me the error : Could not parse the remainder: '[0]' from 'tuple[0]'.
template.html:
{{ tuple[0] }}
views.py:
def fun(request):
tuple=('a','b','c','d')
return render(request,'template.html',{'tuple':tuple})
Simply access tuple as in code below:
{{ tuple.0 }}
Also consider using django built-in template tags to iterate over your data, see simple usage below:
{% for item in tuple %}
<span>
{{ item }}
</spam>
{% endfor %}

Django get_comment_list returns empty list

I've been pulling my hair out over this and can't figure out what's going on.
In my view I can do this:
from django.contrib.comments import Comment
...
context['comments'] = Comment.objects.filter(object_pk = self.kwargs['pk'])
...
Then in my template when I do:
{% for comment in comments %}
{{ comment.comment }}
{% endfor %}
It works perfectly and displays each comment...
However when I try to use the django template tags for comments I get an empty list
{% load comments %}
{% get_comment_list for video as comments %}
{% for comment in comments %}
{{ comment.comment }}
{% endfor %}
{{ comment_list|length }} // displays '0'
video in the above code is the object instance in the template context - I use it elsewhere in the template and it works fine - ie {{ video.title }}, {{ video.id }}
Also - other comment template tags seem to work fine:
{% render_comment_list video %}
displays the test template I have located at comments/list.html - this template just prints out "hello world".
Any idea what's going on here or how to debug it?
Just a guess but, when you do this:
Comment.objects.filter(object_pk = self.kwargs['pk'])
in the view, you aren't specifying a content_type (Video) for the comments you wish to get, so you are retrieving all comments for any object with the id 'pk' - maybe that's why you are seeing comments when you do it manually, but none when you leave it up to the template tag. Maybe the comments aren't attached to the correct ContentType - you could check this in the django admin

Django templates: value of dictionary key with a space in it

In a Django template, is there a way to get a value from a key that has a space in it?
Eg, if I have a dict like:
{"Restaurant Name": Foo}
How can I reference that value in my template? Pseudo-syntax might be:
{{ entry['Restaurant Name'] }}
There is no clean way to do this with the built-in tags. Trying to do something like:
{{ a.'Restaurant Name'}} or {{ a.Restaurant Name }}
will throw a parse error.
You could do a for loop through the dictionary (but it's ugly/inefficient):
{% for k, v in your_dict_passed_into_context %}
{% ifequal k "Restaurant Name" %}
{{ v }}
{% endifequal %}
{% endfor %}
A custom tag would probably be cleaner:
from django import template
register = template.Library()
#register.simple_tag
def dictKeyLookup(the_dict, key):
# Try to fetch from the dict, and if it's not found return an empty string.
return the_dict.get(key, '')
and use it in the template like so:
{% dictKeyLookup your_dict_passed_into_context "Restaurant Name" %}
Or maybe try to restructure your dict to have "easier to work with" keys.
You can use a custom filter as well.
from django import template
register = template.Library()
#register.filter
def get(mapping, key):
return mapping.get(key, '')
and within the template
{{ entry|get:"Restaurant Name" }}