A
A
Andrey_Dolg2019-02-19 13:43:18
Django
Andrey_Dolg, 2019-02-19 13:43:18

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': ['']}>
}

Form code:
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)

Valid in form.is_valid() requires input in hidden input.
A workaround is available by removing the Django field by id in js and it works.
However, looking at other already built-in payment systems, I see that apparently the libraries generate the fields themselves, but they can determine the field already created in the form (with the correct name) and transfer data to it without generating their own field, which helps them work with this Dajngo platform . In general, I would like to have 2 hiddeninputs with different names and the ability to pass a token to the djangoinput field in forms.py. Maybe I'm stupid =)
Django 2.1.5
Python 3.6.6

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey_Dolg, 2019-02-20
@Andrey_Dolg

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)

Just as valid.
And when calling the __init__ method of the Form ancestor, you can specify initial= {'token': token, 'csrfmiddlewaretoken': csrf } or data={...} but before that, clean kwargs from such names. As it is written in the documentation.
As I understand it, this BaseForm fragment is responsible for filling:
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 question

Ask a Question

731 491 924 answers to any question