How to post a array to views.py - django

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!

Related

Obtaining ID of form in a formset

I need a way to set the id of the div that contains each form in a formset to a value that contains a number that is representative of the index of that form.
eg. I want the 2nd form to have a parent div that looks like this
<div id="1"> #id could even be "id_form-1-id".
form
</div>
I've found that {{form.id}} produces the following:
<input type="hidden" name="form-3-id" id="id_form-3-id">
Is there a way that I can extract just the id value (i.e. id_form-3-id) from this string using a template tag?
For reasons that I won't get into, a forloop.counter counter won't reliably return an index as some forms within the formset can be created outside of the typical formset for loop.
Thanks!
You can use auto_id:
{{form.id.auto_id}}

How to convert form data to django?

How to convert form data to django?
I have a html formalary that sends several arrays given. for example:
<input name="item[0]nome"/>
<input name="item[0]descriaco"/>
<input name="item[1]nome"/>
<input name="item[1]descriaco"/>
This comes from the html form
With this I can pass the data to a view in Django using post and at the same time pass an is_valid. Goodbye then.
When trying to grab the dest object items as array, I came across a problem.
The Django Form returns me the key with the name "item[0]name"
Instead of returning an array with:
item[{
"nome": value,
"descricao": value},
{
"nome": value,
"descricao": value}
]
Thank you for attention.
I got it sorted out.
<input name="nome"/>
<input name="nome"/>
<input name="nome"/>...
itens=[]
for item in request.POST.getlist('nome'):
itens.append({
'nome': item
})
Thank you Lemayzeur and cezar

Django QueryDict Result Structure

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.

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!

Django template: Ordering dictionary items for display

I am making a website that displays a user's chosen youtube videos. A user can enter a comment for each video.
I want to display (in this order):
User comment
video title
I have already made the view and have created the following list of dictionary items. Each one represents one video. I send this to my html page:
[
{"my_own_object": vid_obj1, "youtube_obj": obj1}
{"my_own_object": vid_obj2, "youtube_obj": obj2}
]
"youtube_obj" is the object supplied by youtube, which contains the url, title, rating, etc. "my_own_object" contains the user's comments as well as other information.
I iterate over the list and get one dictionary/video. That's fine. Then I need to display the video's information:
{% for key,value in list.items %}
{% if key = "my_own_object" %}
<div>
<p>{{value.user_comment}}</p>
</div>
{% endif %}
{% if key = "youtube_obj" %}
<div>
<p> {{value.media.title.text}}</p>
</div>
{% endif %}
{% endfor %}
This works, except that, because I cannot determine the dictionary order, I might end up with:
Video title
User comment
I thought I could get around this by assigning variables (and then printing the values in the proper order), and am still reeling from the fact that I cannot assign variables!
So, how can I get around this? Can I pluck the key/value that I need instead of iterating over the dictionary items - I tried looking for ways to do this, but no luck. Any other ideas? (I need to pass both video objects as I may need more information than comment and title, later.)
You can use dictionary keys directly:
{% for item in list %} {# PS: don't use list as a variable name #}
<p>{{item.my_own_object.user_comment}}</p>
<p>{{item.youtube_obj.media.title.text}}</p>
{% endfor %}
Just iterate twice. Once for the videos, and once again for the comments. Or, split them into their own dictionaries that are passed through to the template. That's probably a better option, as you avoid iterating twice over the dict. For very small dicts this will be no problem. For larger ones, it can be a problem.