Home > OS >  Django - pass dict from POST form
Django - pass dict from POST form

Time:11-05

There is a from with various elements

<input name='id' value='123'/>
<input name='some_value' value='123'/>
<!-- thing that i want-->
<input name='array[key_1]' value='value_1'/>
<input name='array[key_2]' value='value_2'/>
<input name='array[key_3]' value='value_3'/>
<input name='array[key_4]' value='value_4'/>
</form>

If i've been used PHP, array data will be collected in $_POST["array"] So the questions is, how to collect dict "array" in django views?

CodePudding user response:

Try below code.

views.py:

def DemotimeView(request):
    if request.method == 'POST': 
        data = dict(request.POST)
        del data['csrfmiddlewaretoken']
        print({i:j[0] for i,j in data.items()})
    return render(request, 'index.html',)

Html:

<form action="" method="post">
     {% csrf_token %}
     <input name='id' value='123'/>
     <input name='some_value' value='123'/>
     <!-- thing that i want-->
     <input name='key_1' value='value_1'/>
     <input name='key_2' value='value_2'/>
     <input name='key_3' value='value_3'/>
     <input name='key_4' value='value_4'/>

     <button type="submit">Add</button>

</form>

Output:

{'id': '123', 'some_value': '123', 'key_1': 'value_1', 'key_2': 'value_2', 'key_3': 'value_3', 'key_4': 'value_4'}

CodePudding user response:

You can get all values of the form in the view by giving their name attribute in request.POST dict so:

def some_view(request):
    if request.method=='POST':
       id=request.POST.get('id')
       some_value=request.POST.get('some_value')

CodePudding user response:

I'm not sure that it's the best way, but it's work. I've decide to rename params without [] and combine them with dict key with separator "__"

So, here it is

template:

<input type="text" name="name" 
        value='Yuretz'/>
<input type="text" name="last_name" 
        value='Oguretz'/>

{% for line in print_values %}
<div>
   <b>{{line.name}}</b><br/>
   <input type="text" 
      name="param__{{line.name}}"
      value="{{line.value}}"/>
</div>
{% endfor %}

views.py

params_data = {}    
all_post_data = request.POST.dict()
for line in all_post_data:
   if line.startswith('param__'):
       params_key = line.replace('param__','')
       params_value = all_post_data[line]
       params_data[params_key]=params_value
### finally
print(params_data)

Hope that will help somebody

  • Related