So I'm creating a form object using request.POST data, but want to initialise additional fields using other values. This is what i tried, it isn't working:
#forms.py
class InputForm3(forms.Form):
url = forms.URLField(required=True)
db = forms.CharField(required=False)
wks = forms.CharField(required=True, initial="Sheet1")
table = forms.CharField(required=False, initial="test_table")
def __init__(self, wks, *args, **kwargs):
self.wks=wks
super().__init__(*args, **kwargs)
self.cleaned_data = None
def clean(self):
self.cleaned_data = super().clean()
print("FORM3 cleaned_data : ", self.cleaned_data)
#views.py
form3=InputForm3(wks="Sheet1", data= request.POST)
if form3.is_valid:
#remaining code
#output
FORM3 cleaned_data : {'url': 'https://randomurl.com', 'db': 'testdb', 'table': ''}
the fields 'url' and 'db' are present directly in request.POST, HOW DO I INITIALISE THE OTHER FIELDS PLEASE HELP!
Not sure of the context of why you'd want to do that.
But maybe you can try copying the form's data
after you initialized the form with the request.POST
data
. You'll have access to modify the copied data
. For example:
If you're using a function-based view
:
def view_name(request):
form3 = InputForm3(request.POST)
if request.method == "POST":
form3 = InputForm3(data=request.POST) # removing wks from the parameter here...
# assigning the copied collection of data to the form's data so we can modify it
form3.data = form3.data.copy()
form3.data['wks'] = 'Sheet1' # or whatever name you wish to name that wk
if form3.is_valid():
# remaining code
...
If you're using a class-based view
:
def post(self, request, *args, **kwargs):
form3 = InputForm3(data=request.POST)
form3.data = form3.data.copy()
form3.data['wks'] = 'Sheet1'
if form3.is_valid():
# remaining code
...
That worked for me.