Home > Net >  How to generate a list of request.POST in Django
How to generate a list of request.POST in Django

Time:07-26

I have the following code in views.py:

def valores(request):
    global peso_unitario, preco_unitario
    peso_unitario=[]
    preco_unitario=[]

    N=a
    print('N=' str(N))

    for i in range(N):
        peso_u = request.POST['peso_u']
        preco_u = request.POST['preco_u']

        if peso_u.isdigit() and preco_u.isdigit():
            c = int(peso_u)
            d = int(preco_u)
            peso_unitario.append(c)
            preco_unitario.append(d)
            print(a)
            if i==N-1:
                return render(request, 'pacote.html', {'peso_unitario': peso_unitario, 'preco_unitario': preco_unitario})
        else:
            res = 'Apenas numero.'
            return render(request, 'pacote.html', {'res': res})

One step before, where we filled a text field with a number N. Now, I'd like to generate N text fields to be filled by the user, but I don't know how to do this.

CodePudding user response:

You should use a formset to generate N forms dynamically. You can refer to the documentation to see how to implement one.

CodePudding user response:

Don't use globals. You need to store the previously retrieved number N somewhere. Maybe in the user's session. Maybe pass it to this view as a querystring, and have a default value or redirect back to the form which should have obtained it if its missing.

Anyway, having obtained that N, you can build the form with N similar forms dynamically. (As mentioned by others, another way is to use a formset).

class Baseform( forms.Form):
   ...
   # everything apart from the variable  fields

fields = {}
for n in range(N):
     fields[ f'form_{n}'] = forms.Charfield( # or whatever
         label = f'form{n}', ... # other form args
     )

My_Dynamic_Form = type(
    'My_Dynamic_Form',  (BaseForm, ), fields
)

Instantiate, check as usual, process the variable fields:

form = My_Dynamic_Form( ...)
if form.is_valid():
    # your variable data will be in form.cleaned_data['form_0'] upwards.
    # maybe
    for n in range(1000):
        key = f'form_{n}'
        if not (key in form.cleaned_data):
            break
        val = form.cleaned_data.get(key)
        # do whatever with val 
  • Related