Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change form input attribute 'name' to 'data-encrypted-name'

This was a tricky question to title, so please read before assuming its a duplicate :).

I'm using Braintree Payments on a Django site, and the payment form html needs to look like this for the credit card number:

<input type="text" size="20" autocomplete="off" data-encrypted-name="number" />

mine currently looks like this:

<input type="text" size="20" autocomplete="off" name="number">

Can I somehow rename name to data-encrypted-name? Alternatively, can I hide/remove the name attribute altogether? If so, I could then easily add a custom attribute for the Braintree-friendly attribute:

class SignupForm(forms.Form):
    ...snip...

    def __init__(self, *args, **kwargs):
         super(SignupForm, self).__init__(*args, **kwargs)

         self.fields['number'].widget.attrs['data-encrypted-name'] = "number"

FYI I tried this in the __init__ but no luck:

         self.fields['number'].widget.attrs['name'] = None

Per Braintree:

IMPORTANT: Do not use the name attribute for any fields that capture sensitive payment information such as the credit card number or CVV. Removing this attribute prevents them from hitting your server in plain text and so reduces your PCI compliance scope.

Also, I'm using django crispy forms, so I'd prefer to solve this in my forms.py and not in the template with html tweaks in order to keep it DRY.

like image 565
Banjer Avatar asked Jan 12 '23 16:01

Banjer


1 Answers

Define a custom widget class inheriting from whatever widget type your numbers field defaults to (TextInput, judging from the tag you're showing) and override its build_attrs method.

I'd do it something like this:

class SensitiveTextInput(TextInput):
    def build_attrs(self, extra_attrs=None, **kwargs):
        attrs = super(SensitiveTextInput, self).build_attrs(extra_attrs, **kwargs)
        if 'name' in attrs:
            attrs['data-encrypted-name'] = attrs['name']
            del attrs['name']
        return attrs

If you need to do this for more than a handful of widget types you could abstract this into a mixin.

like image 111
Peter DeGlopper Avatar answered Jan 17 '23 10:01

Peter DeGlopper