Skip to content

Commit

Permalink
feat(vote): add ImageField with validation size and type
Browse files Browse the repository at this point in the history
  • Loading branch information
igr-santos committed Aug 30, 2024
1 parent ad85117 commit 5ff4719
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 622 deletions.
35 changes: 29 additions & 6 deletions app/org_eleicoes/votepeloclima/candidature/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,14 +162,14 @@ def __init__(
text_help_text=None,
help_text=None,
attrs=None,
max_length=None
max_length=None,
):

if attrs is None:
attrs = {}
if max_length:
attrs['maxlength'] = max_length
attrs["maxlength"] = max_length

widgets = [
SwitchInput(
attrs={"data-checktext": ""}, label=checkbox_label, help_text=help_text
Expand Down Expand Up @@ -232,7 +232,7 @@ def __init__(
text_label=text_label,
text_help_text=text_help_text,
help_text=help_text,
max_length=max_length
max_length=max_length,
)

super().__init__(
Expand Down Expand Up @@ -461,6 +461,29 @@ def clean(self, value, initial):
return value


class ImageField(forms.ImageField):

def __init__(
self, *, max_size=10, max_length=None, allow_empty_file=False, **kwargs
):
super().__init__(
max_length=max_length, allow_empty_file=allow_empty_file, **kwargs
)
# 10MB
self.max_size = max_size * 1024 * 1024
self.widget.attrs["accept"] = "image/png,image/jpeg"

def clean(self, value, initial):
value = super().clean(value, initial)
if value.size > self.max_size:
raise forms.ValidationError(
"Por favor, escolha uma imagem com tamanho de até %s. Tamanho Atual %s"
% (filesizeformat(self.max_size), filesizeformat(value.size))
)

return value


class HTMLBooleanField(forms.BooleanField):

def get_bound_field(self, form, field_name):
Expand All @@ -477,4 +500,4 @@ class ButtonCheckboxSelectMultiple(forms.CheckboxSelectMultiple):

class ButtonRadioSelect(forms.RadioSelect):
template_name = "forms/widgets/button_input_select.html"
option_template_name = "forms/widgets/button_input_option.html"
option_template_name = "forms/widgets/button_input_option.html"
Loading

0 comments on commit 5ff4719

Please sign in to comment.