Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove_attr doesn't remove the required attribute #105

Open
pan-m opened this issue Feb 13, 2021 · 2 comments
Open

remove_attr doesn't remove the required attribute #105

pan-m opened this issue Feb 13, 2021 · 2 comments

Comments

@pan-m
Copy link

pan-m commented Feb 13, 2021

When trying to do {{ form.field | remove_attr:'required' }} as proposed in #63, the resulting <input> still has the "required" attribute.
If I have understood the code correctly, at least in the case of django stock authentication forms, this happens because the "required" attribute is not initially included in field.field.widget.attrs, but rather is set by the BoundField class in the build_widget_attrs() method at a later stage after the filter has run. Probably the same happens with the "disabled" attribute.

Code references:

@register.filter("remove_attr")
@silence_without_field
def remove_attr(field, attr):
    if attr in field.field.widget.attrs:
        del field.field.widget.attrs[attr]
    return field

django-widget-tweaks/widget_tweaks/templatetags/widget_tweaks.py

def build_widget_attrs(self, attrs, widget=None):
    widget = widget or self.field.widget
    attrs = dict(attrs)  # Copy attrs to avoid modifying the argument.
    if widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute:
        attrs['required'] = True
    if self.field.disabled:
        attrs['disabled'] = True
    return attrs

django/django/forms/boundfield.py

A possible solution would be:

@register.filter("remove_attr")
@silence_without_field
def remove_attr(field, attr):
    if attr == "required":
        field.field.required = False
    else:
        if attr in field.field.widget.attrs:
            del field.field.widget.attrs[attr]
    return field
@zodman
Copy link
Member

zodman commented Feb 16, 2021

the required it comes with a Form. only define not required on the form and attribute will not showup

@alexandremjacques
Copy link

I guess the use case here is the HTML5 validation that is triggered with required being set on the field.
The one possible work-around I found is setting novalidate on the <form> tag (<form novalidate action...>).
If the rendered field have the required attribute, not even formnovalidate on it is going to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants