问题
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