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

It was a tricky question for the title, so please read it before reading its duplicate :).

I use Braintree Payments on the Django website and the html payment form should look like this: 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"> 

Is it possible to somehow rename name to data-encrypted-name ? As an alternative, is it possible to hide / remove the name attribute altogether? If so, I could easily add a custom attribute for the Braintree compatible 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 __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, for example, credit card number or CVV. Removing this attribute prevents them from hitting your server in plain text and therefore reduces the PCI compliance area.

In addition, I use django crispy forms , so I would prefer to solve this in my forms.py rather than in a template with html settings to save DRY.

+4
source share
1 answer

Define a custom widget class that inherits from any type of widget, the numbers field is set by default ( TextInput , judging by the tag that you display) and override its build_attrs method.

I would 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 few types of widgets, you can abstract this into mixin.

+9
source

Source: https://habr.com/ru/post/1495866/


All Articles