I'm completely newbie in Django-phython.
I'm trying to populate the results of a search inside an html form input tag. with the register that the search returns.
I have a view that renders an html code, passing a dictionary. And I would like to display that dictionary, containing the search results, inside the html form fields that corresponds to that dictionary.
The question is if it's possible to do such a thing.
You will get all the information at django template documentation
Specifically, if you want to iterate through the dictionary in your template, you need the for loop.
From the documentation:
This can also be useful if you need to access the items in a
dictionary. For example, if your context contained a dictionary data,
the following would display the keys and values of the dictionary:
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
You'll have to use ajax and a typehead pulgin for that.
Related
This question already has answers here:
Django template how to look up a dictionary value with a variable
(8 answers)
Closed 4 years ago.
So I have a nested dictionary in the form of the following:
data = { server:{'rating':{'class':'good, 'desc':'whatever'}, 'vulnerabilities':{'heartbleed':{'severity':'critical', 'desc':'terrible config'}}
I want to iterate through the values using keys, I've read the documentations and this is what I do in template:
{% for key, value in data.items %}
<p> 'This is the key {{ key }} and this is the value {{value}}'<p>
{% endfor %}
so far so good, the bizarre thing is that I can`t get the values using the key retrieved by the for loop, namely, when I have such a template:
{% for key in data.keys %}]
<p> 'This is the key: {{key}}' </p>
<p> 'This is the value: {{ data.key }}'<p>
{% endfor %}
{{key}} returns the keys with no problem. Even when I do {{data.server}} I get the corresponding values with no problem. Strange thing is that this line {{data.key}} does not work as I intuit it to.
In one loop the key==server, {{data.server}} works but {{data.key}} does not. What am I getting wrong here?
Only way to this dynamically in template engine is to use custom template filter
Take a look at Django template how to look up a dictionary value with a variable for primer implementation
Some slightly related questions have been asked about this, but the answers did not really help me. When I tried to implement a potential good hint suggested elsewhere (custom templates), I did not get the desired results.
In my template, I am iterating over a set of keys from a dictionary. The dictionary itself originates from submitting a Django formset.
XML Template snippet: (I am rendering to an XML file)
{% for x in range %}
<file type="{{ form-'x'-type }}" viewpath="{{ form-'x'-file }}"/>
{% endfor %}
The above obviously does not work. The iteration works. The rangevariable is a python argument corresponding to range(int(request.POST['form-TOTAL_FORM'])) passed from the view to the XML template.
At every iteration in the template, I need {{ form-0-type }}, {{ form-1-type}}, {{ form-2-type }}, etc.
How do I do that? If I really need to use a custom filter for this, how do I do this?
I hope this question (and the answers) will help many having the same problem.
Thanks.
Edit:(Dictionary posted)
<QueryDict:
{
u'form-MAX_NUM_FORMS': [u'1000'],
u'form-INITIAL_FORMS': [u'0'],
u'form-TOTAL_FORMS': [u'2'],
u'form-0-type': [u'1'],
u'form-1-type': [u'2'],
u'csrfmiddlewaretoken': [u'LpkjdDcqRCL4VPM0SAuU7efgZjgeubTN']
}>
Additional note:
In a second view, I lookup the values for the foreign keys and put the values in another dictionary, which I send to my XML template.
Snippet of the code that does this:
detailed_request = {}
for x in range(0, int(request.POST['form-TOTAL_FORMS'])):
detailed_request['form-'+str(x)+'-type'] = Upload_Type.objects.get(pk=request.POST['form-'+ str(x)+'-type'])
detailed_request['form-'+str(x)+'-file'] = request.FILES['form-'+str(x)+'-file']
The above is a working snippet. When I trace detailed_request, I have all the information I need:
{
'form-1-type': <Upload_Type: malib>,
'form-0-type': <Upload_Type: axf_file>
}
Just in case somebody has the same problem, I actually changed the way I do things.
I do not iterate the formset in the template. Instead, I implemented the solution from Paolo Bergantino here:
Dynamically adding a form to a Django formset with Ajax
Then in my views, I simply get every data I need from request.FILES
I hope that helps anybody who started with the same wrong approach.
You can access the for loop helper variables through the following variables
forloop.counter The current iteration of the loop (1-indexed)
forloop.counter0 The current iteration of the loop (0-indexed)
More at: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
So you'd do...
{{ form }}-{{ forloop.counter }}-{{ type }}
Hi all not sure how to explain this clearly but here goes....
I need to use two variables like so:
{% for client in clients %}
{% if user.client.username %}
I need {% if user.username %} but the value of username is in client.username from the loop.
is there a way to do this?
If I understand correctly, user is a dict, and you want to lookup the value indexed by client in each iteration of the loop - eg, user[client].username in Python.
This (deliberately) isn't possible in Django templates - the language is limited, to force you to do pre-processing in code.
Instead, you should zip your two lists/dicts together before passing them to the template.
Are you trying to do something if the value of client.username is equal to the value of user.client.username? If so, you want:
{% if client.username == user.client.username %} # Works in Django 1.2 and above
{% ifequal client.username user.client.username %} # Works everywhere
I have a formset created using inlineformset_factory. It doesn't matter what it looks like to answer this question. In the template I am looping through it with for form in forms.formset:
I want to be able to display the form index of the form in my template. By form index, I mean the number associated with that form in all of the formfields. Is there a variable that does this? I tried form.index and form.form_id and form.id is a field.
No, objects in a collection don't generally have access to their index or key.
However if you're outputting the formset in a template, you're presumably looping through the forms. So you can use {% forloop.counter %} to get the index of the iteration.
Although it is not pretty, based on the formset source and the comment by #yuji-tomita-tomita above, you could do something like this in your template:
{{ form.prefix|cut:formset.prefix|cut:'-' }}
This just takes the form prefix string, which includes the form index, then removes the irrelevant parts. In the view you could simply do e.g. form.prefix.split('-')[1].
I have a list that is passed into a template. I want to access a value with a specific index. Problem is the list is accessed with dot notation in the template...
For example:
object = { id: 1 }
list = [ "zero", "one" ]
print list[ object.id ] ## one
Once the list is in the template you access values by index with dot notation.
list.1 ## one
list[ object.id ] ## this doesn't work
list.object.id ## this doesn't work obv.
How can I access the value "one" with the index of "1"?
Thanks in advance!
I don't think this is possible with Django's template language. It is pretty limited by design.
You can do this by putting that code in the view, and passing the value of list[object.id] down to the template when you render it.
I don't quite agree it's impossible.
You can create template tag, which will accept two arguments and will inject a new
variable into a template context.
The usage can look as follows:
{% get_list_member list object.id as list_member %}
then you can use list_member as ordinary template variable {{ list_member }}
check the implementation of standard url template tag, which also allows to assign url into
template context variable for later use.