jonashaag / django-addanother

"Add another" buttons outside the Django admin
http://django-addanother.readthedocs.org/
ISC License
50 stars 18 forks source link

Remove empty label duplicate #47

Closed sterliakov closed 2 years ago

sterliakov commented 2 years ago

django_select2 adds an empty option to rendered select under some conditions. With this PR we can detect then and remove the empty label back by subclassing the widget. Execution cannot be lazy (code in select2 calls list() anyway).

sterliakov commented 2 years ago

I can't actually post a screenshot, this issue is invisible (select options are not shown as dropdown when select2 is used). However, html validation fails in this case. Sorry for not having described the issue initially, idk what i had in mind. First of all, steps to reproduce (starting from test project in your repo):

  1. (Should I open issue for that?) requirements allow Django>=2.2, however, with current Django==4.0 test project fails to run due to ImportError's. Install Django<4.0 instead.
  2. Install django-select2 and django-redis. Configure them according to docs. Make sure redis is running (from docker image, as package or somehow else).
  3. Modify testapp/forms.py to look like below:
    
    from django import forms
    try:
    from django.core.urlresolvers import reverse_lazy
    except ImportError:
    from django.urls import reverse_lazy

from django_addanother.contrib.select2 import Select2AddAnotherEditSelected # add this line from django_addanother.widgets import AddAnotherWidgetWrapper, AddAnotherEditSelectedWidgetWrapper

from .models import Player

class PlayerForm(forms.ModelForm): class Meta: model = Player fields = ['name', 'current_team', 'future_team', 'previous_teams'] widgets = { 'current_team': AddAnotherWidgetWrapper( forms.Select(), reverse_lazy('add_team'), ), 'future_team': Select2AddAnotherEditSelected( # change widget here reverse_lazy('add_team'), reverse_lazy('edit_team',args=['fk']), ), 'previous_teams': AddAnotherWidgetWrapper( forms.SelectMultiple, reverse_lazy('add_team'), ) }

3. Run server and go to desired page. Inspect html rendered.

*Problem description*
Rendered html is invalid (first option has both empty value and empty content, [validator](https://github.com/validator/validator/) complains:
> The first child “option” element of a “select” element with a “required” attribute, and without a “multiple” attribute, and without a “size” attribute whose value is greater than “1”, must have either an empty “value” attribute, or must have no text content. Consider either adding a placeholder option label, or adding a “size” attribute with a value equal to the number of “option” elements.

With my patch:
jonashaag commented 2 years ago

Thanks for the patch!