Answer the question
In order to leave comments, you need to log in
How to override initial data in django form?
Greetings.
From the form in Django comes a token that is generated by the payment system. I am declaring a form with one hidden field that accepts a token. Js liba of the payment system creates its own form and generates input fields. If the names of the hidden input django and the payment system match (we get 2 hidden input), the token does not come anywhere and we get ''Token'' : [" "," "]. When changing the field name in the Django code, we get a token by the js name of the form "Token":["token"], "Djangoinput"[" "]. The essence of the problem is that I do not want to change platform views , but limit myself to changes in the forms.py file for this particular payment system.
Briefly, then? override the parameters included in the form, and write a token to Djangoinput,
What comes in **kwargs __init__ of the form.
{'data':
<QueryDict: {'csrfmiddlewaretoken': ['****'],
'Token': ['tokn_test_5ezewjccegvcnzm6exn'],
'Source': [''],
'Djangoinput': [''],
'username': ['']}>
}
class PaymentForm(forms.Form):
Djangoinput = forms.CharField(widget=forms.HiddenInput, required=True)
def __init__(self, payment_information, gateway_params, *args, **kwargs):
token = None
initial_arguments = kwargs.get('data', None)
if initial_arguments:
token = initial_arguments.get('Token', None)
csrf = initial_arguments.get('csrfmiddlewaretoken', None)
# Now update the form's initial values
if token:
data_test={}
data_test['Djangoinput'] = [token,]
data_test['csrfmiddlewaretoken'] = csrf
kwargs.update({'data' : data_test})
super(PaymentForm, self).__init__(*args, **kwargs)
self.fields['Paymentforms'] = forms.CharField(
widget=PayCheckoutWidget(
payment_information=payment_information,
gateway_params=gateway_params),
required=False)
Answer the question
In order to leave comments, you need to log in
In general, the error seems to have disappeared. =)
More readable code.
class PaymentForm(forms.Form):
token = forms.CharField(widget=forms.HiddenInput, required=True)
def __init__(self, payment_information, gateway_params, *args, **kwargs):
initial_arguments = kwargs.get('data', None)
if initial_arguments:
token = initial_arguments.get('Token', None)
csrf = initial_arguments.get('csrfmiddlewaretoken', None)
if token:
kwargs.update({'data':{'token':token, 'csrfmiddlewaretoken': csrf }})
super(OmisePaymentForm, self).__init__(*args, **kwargs)
def _clean_fields(self):
for name, field in self.fields.items():
# value_from_datadict() gets the data from the data dictionaries.
# Each widget type knows how to retrieve its own data, because some
# widgets split data over several HTML fields.
if field.disabled:
value = self.get_initial_for_field(field, name)
else:
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question