Django QueryDict Result Structure - django

What is resulting querydict structure from a post in django? Here is an example for a radio button.
A single key in the QueryDict:
u'Q1', [u' ', u'1', u' ']
In the list for Q1 position 1 is the selected value, what are positions 0 and 2 representing? Here is another example for "select/drop down" type HTML input. What do the positions represent here? Position 2 is now the response but what are positions 0 and 1?
u'Q6', [u'1', u'1', u'4']
What about a text field?
u'Q8', [u'', u'', u'Joe']
I've looked through the documentation and haven't found the answer or I'm blinding looking right past it.

Seems like you put three similar django forms inside the single <form> tag:
<form method="POST">
{% csrf_token %}
{{ form }}
{{ form }}
{{ form }}
</form>
If you want to output several instances of the same form class then consider to use the prefix argument in the form constructor or even the formsets mechanizm.

Related

rounding django input field makes it dissapear

I have a decimal field in my form.
The input displays values like: 60.00
I want it to display: 60
I have tried:
{% load humanize %}
{{ form.amount|floatformat }}
I have also tried changing my form field to an integer:
class AmountInfoForm(forms.ModelForm):
amount = forms.IntegerField()
class Meta:
model = Customer
fields = ('amount',)
This causes the field to disappear.
What am I doing wrong?
I am afraid I see that you are applying floatformat to an input element and not to a valid numeric value. As a consequence, it fails to show and thus Django prefers not to show anything at all.
You could try this workaround then:
First of all, please try printing your form this way:
{{ form.as_table }}
If you look at the source code, you could see that, for example, the input for the field called name is displayed this way:
<input id="id_name" name="name" maxlength="25">
As a consequence, you can emulate this behaviour doing the following in your django template:
<input id="id_{{form.amount.label}}" name="{{form.amount.label}}" maxlength="25" value={{form.amount.value|floatformat:0}}>
Overall,the secret is to apply floatfomat to form.amount.value instead of form.amount.
Hope it works for you!

How to post a array to views.py

I am using for loop in my template and for different id of each record i am using arrays
{% for item in product %}
<div class="register_div">
<p><label for="id[{{ item.id }}]">{{ item.Name }} </label> <input type="text" name="custom[{{item.id}}]"/></p>
</div>
{% endfor %}
Now when in my views i want to save this data to my database.But firstly i checked that whether my array return something or not.So i just try print that as.
q = upload_form.data['custom[]']
or
q = upload_form.data['custom']
but it gives me this error
"Key 'custom[]' **OR** key custom not found in <QueryDict: {u'custom[2]': [u's'], u'custom[1]': [u'a'], u'price': [u''], u'title': [u''], u'customatt': [u'', u''], u'csrfmiddlewaretoken': [u'up4Ipd5L13Efk14MI3ia2FRYScMwMJLz']}>"
but if i print this
q = upload_form.data['custom[1]']
then it display the value of array 1.
so please suggest me a better way to do this how i can display all values inside my array in views.py
As upload_form.data is a dictionary, the key 'custom[]' simply doesn't exist. Try something like:
custom_values = {}
for key, value in in upload_form.data.items():
if key.startswith('custom'):
custom_values[key]=value
The dictionary custom_values holds now all your 'custom' form values.
This is not an answer to question, but:
You are not posting an array, but different inputs whose name looks like accessing array. e.g. you are posting different input variables named custom[1], custom[2] etc. But custom is not an array, you will have to access inputs as custom[1] etc.
I'm not sure you want this or not!

Can Django write JSON to an input and use it in a template as well as read it back?

This uses Django with Python 2.5. I have a list of dicts that I want to write to a template variable in a view and also be able to recover the list when the form is submitted. I am only able to do one or the other.
When I use render_to_response with the list of dicts, I can use the value in the template, but the keys are single-quoted so simplejson.loads fails. If I convert the list of dicts using simplejson.dumps before render_to_response, I can recover the list with loads, but the template sees the variable as a string.
To both use the variable in the template and recover the list later, I need to write to two inputs in the view. It seems like I'm missing something.
Here is an example.
test.py:
from django.shortcuts import render_to_response
from django.utils import simplejson
def test(request):
test_dict_list = [{'a': 1, 'b': 2, 'c': 3}, {'d1': 4,'e2': 5}]
test_dict_list_json = simplejson.dumps(test_dict_list)
str1 = request.GET.get("test_dict_list")
# u"[{'a': 1, 'c': 3, 'b': 2}, {'e2': 5, 'd1': 4}]"
try:
simplejson.loads(str1)
# fails because keys are single-quoted
except:
pass
str2 = request.GET.get("test_dict_list_json")
# u'[{"a": 1, "c": 3, "b": 2}, {"e2": 5, "d1": 4}]'
try:
list1 = simplejson.loads(str2)
# correct list of dicts since keys are double quoted
# [{u'a': 1, u'c': 3, u'b': 2}, {u'd1': 4, u'e2': 5}]
except:
pass
return render_to_response('testview.html',
{'test_dict_list': test_dict_list,
'test_dict_list_json': test_dict_list_json})
testview.html:
<h1>Testing</h1>
<form name="test_form" action="{% url test %}" method="get">
<h3>test_dict_list = {{ test_dict_list }}</h3>
{% for elt in test_dict_list %}
<ul>{{ elt }}</ul>
{% endfor %}
<h3>test_dict_list_json = {{ test_dict_list_json }}</h3>
{% for elt in test_dict_list_json %}
<ul>{{ elt }}</ul>
{% endfor %}
<input name="test_submit" type="submit" class="cpa-button" value="Test submit"/>
{# Invisible input to store persistent values across page loads #}
<input name="test_dict_list" type="text" style="display:none" value="{{ test_dict_list }}"/>
<input name="test_dict_list_json" type="text" style="display:none" value="{{ test_dict_list_json }}"/>
</form>
I'm not sure why you think you are missing something. JSON is a text interchange format. If you dump a dict to JSON, it is converted to a string, and you can't iterate through its items. If you simply output a dictionary as a string, it will not be valid JSON. Python's dictionary literal format is close to JSON, but not exactly the same.
How about creating a templatetag for converting the dictionary into a JSON string from within the template? Custom template tags are very powerful and surprisingly easy to write. More info here.
Why are you sending json to the template in the first place?
You can render from a dictionary in a template using a for loop
{% for key,value in my_dictionary.items %}
<li>{{key}}:{{value}}</li>
{% endfor %}
Furthermore - don't encode to json and store in a webpage just so you can send it back to yourself again -- this is what sessions (or messages) are for. In your views do this:
request.session['mydict'] = my_dictionary
On the next view, you can simply recover the dictionary with
request.session['mydict']
I'd suggest checking to make sure 'mydict' in request.session though and handle failure accordingly, just to be safe.

Django ChoiceField get currently selected

I have a simple ChoiceField and want to access the 'selected' item during my template rendering.
Lets say the form gets show again (due to error in one of the fields), is there a way to do something like:
<h1> The options you selected before was # {{ MyForm.delivery_method.selected }} </h1>
(.selected() is not working..)
Thanks !
#Yuji suggested bund_choice_field.data, however that will return value which is not visible to user (used in value="backend-value"). In your situation you probably want literal value visible to user (<option>literal value</option>). I think there is no easy way to get literal value from choice field in template. So I use template filter which does that:
#register.filter(name='choiceval')
def choiceval(boundfield):
"""
Get literal value from field's choices. Empty value is returned if value is
not selected or invalid.
Important: choices values must be unicode strings.
choices=[(u'1', 'One'), (u'2', 'Two')
"""
value = boundfield.data or None
if value is None:
return u''
return dict(boundfield.field.choices).get(value, u'')
In template it will look like this:
<h1> The options you selected before was # {{ form.delivery_method|choiceval }} </h1>
UPDATE: I forgot to mention an important thing, that you will need to use unicode in choice values. This is because data returned from form is always in unicode. So dict(choices).get(value) wont work if integers where used in choices.
It would be accessed by {{ myform.delivery_method.data }}
<h1> The options you selected before was # {{ MyForm.delivery_method.data }} </h1>

How to get form fields' id in Django

Is there any way to get the id of a field in a template?
In the HTML I get: <input name="field_name" id="id_field_name"...
I know I can get the name with {{ field.html_name }}, but is there anything similar for getting the id?
Or can I only get it like this: id_{{ field.html_name }}?
You can get the ID like this:
{{ field.auto_id }}
You can also use id_for_label:
{{ field.id_for_label }}
This doesn't work for every form field.
For instance {{ form.address.auto_id }} works while {{ form.address.auto_name }} will not.
However you can use {{ form.address.html_name }} to get the equivalent answer.
Here are the docs
From the documentation-
each form field has an ID attribute set to id_<field-name>
, which is referenced by the accompanying label tag. This is important in ensuring that forms are accessible to assistive technology such as screen reader software. You can also customize the way in which labels and ids are generated.
So I would like to say id_field-name , you collect the field name from the model.
Here is the link to the documentation
In Django 2 you can retrieve the ID for a specific field using {{ field.id_for_label }}
This is documented here.