0

I would like to realize this scenario: I want to have a simple form, containing some text fields and multiple submit buttons. When I click a button, the action for this button should be performed and the appropriate form fields should be updated. Let us say, we have an encryption demo. When I press encrypt, the plaintext is read and written encrypted into the ciphertext field and so on.

I have a very simple form:

from django import forms

class ABEForm(forms.Form):
    master_private_key = forms.CharField(required=False,label="Master Secret Key",widget=forms.Textarea(attrs={'width':"100%", 'cols' : "80", 'rows': "20", }))
    master_public_key = forms.CharField(required=False,label="Master Public Key",widget=forms.Textarea(attrs={'width':"100%", 'cols' : "80", 'rows': "20", }))

And a also quite simple view for that:

def form_submit(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        #check what submit button was pressed
        if 'abe_setup' in request.POST:
            form = ABEForm(request.POST)
            abesetupdata = ABE_Scheme_SetupData()
            abesetupdata.init_setup()
            form.master_private_key = abesetupdata.master_key
            form.master_public_key = abesetupdata.master_public_key
            print("privkey =>", form.master_private_key)
            print("pubkey =>", form.master_public_key)
            return render(request, 'webfrontend/abeform.html', {'form': form})
        elif 'abe_keyen' in request.POST:
            return render(request, 'webfrontend/abeform.html', {'form': form})


    # if a GET (or any other method) we'll create a blank form
    else:
        form = ABEForm()
        return render(request, 'webfrontend/abeform.html', {'form': form})

The case handling (which button was pressed) seems to be fine. The form, however, is empty whenever I press the setup button and the form gets re-rendered. What did I miss? I know you can provide a dictionary to bind data to a form. But using request.POST as a data source should work, correct? The print statements do work and print the form contents to the command line...

JSON C11
  • 11,272
  • 7
  • 78
  • 65
Fluffy
  • 299
  • 1
  • 4
  • 21

1 Answers1

0

I figured that forms are immutable when unbound and field data cannot be assigned. I have to create new form, passing a dictionary in there like this:

        data = {'master_private_key': abesetupdata.master_private_key,
            'master_public_key': abesetupdata.master_public_key,
            'attribute_key' : abesetupdata.attribute_key,
        }
        form = ABEForm(data)
Fluffy
  • 299
  • 1
  • 4
  • 21