Override Django form field's name attr

前端 未结 5 1720
谎友^
谎友^ 2020-12-05 11:23

I\'ve built a Django form that submits to a page on another domain (that I don\'t control). The idea is that I have a nicely styled, neatly generated form that fits neatly i

5条回答
  •  时光取名叫无心
    2020-12-05 11:53

    I realize this question is old, but here's another (possibly cleaner) way to do it. Most of the answers here involve monkey patching or overriding a superclass method. This does as well, but I think it's a clean way to do it.

    Create a new Widget that extends the widget you need, such as TextInput:

    class TextInputSansName(forms.TextInput):
        def build_attrs(self, extra_attrs=None, **kwargs):
            if extra_attrs:
                extra_attrs.pop('name', None)
            kwargs.pop('name', None)
            return super().build_attrs(extra_attrs, **kwargs)
    

    Django calls build_attrs on a widget during the render() operation. In the method, I'm removing 'name' if it is in either of the dictionaries. This effectively removes the name just before it renders.

    This answer overrides as little as possible of the Django API.

    In one of my sites, the payment processor needs inputs to be without names. Here's the control declaration in the form class:

    card_number = forms.IntegerField(
        label='Card Number', 
        widget=TextInputSansName(attrs={ 'data-stripe': 'number' })
    ) 
    

    Cheers.

提交回复
热议问题