showing the validation error on the label instead of the input

Deadly 提交于 2020-12-15 06:14:27

问题


I am building a form using a model form with Django and to override the actual design for the input file, I set the input to hidden and used the label instead as a button to upload the image for the field avatar in my code, this was working fine (used this solution: https://youtu.be/4p2gTDZKS9Y) but the problem that I have faced is the field avatar is required, as the input is hidden, the validation error is not appearing as it is also hidden with the input is there any way to show the validation error on the label instead of the input? here my code:

<label for="id_avatar" class="flex items-center h-8 px-4 mx-6 text-xs bg-gray-200 rounded-full text-blue-400 cursor-pointer hover:bg-gray-400 flex-shrink-0 w-34 text-center">
            {% translate "upload image" %}
        </label>
            {{ profilepage_form.avatar }}
            {% if profilepage_form.avatar.errors %}
                <div class="text-red-700 px-4 py-3" role="alert">
                    <strong>{{ profilepage_form.avatar.errors|escape }}</strong>
                </div>
            {% endif %}

and here where I added the css deign on the form.py

class UserProfileDetailsForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = [
            "avatar",
        ]

    def __init__(self, *args, **kwargs):
        super(UserProfileDetailsForm, self).__init__(*args, **kwargs)
        self.fields["avatar"].widget.attrs["class"] = "flex items-center h-8 px-4 ml-6 text-xs bg-gray-200 rounded-full hidden"
        self.fields["avatar"].required = True

I am using tailwind -> the class hidden means indeed: display: none

here an example of how the error message is appearing on one required field but not appearing on the upload image label as the input is hidden:

来源:https://stackoverflow.com/questions/65030844/showing-the-validation-error-on-the-label-instead-of-the-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!