def test_widget_attrs_default_accept(self):
     f = ImageField()
     # Nothing added for non-FileInput widgets.
     self.assertEqual(f.widget_attrs(Widget()), {})
     self.assertEqual(f.widget_attrs(FileInput()), {'accept': 'image/*'})
     self.assertEqual(f.widget_attrs(ClearableFileInput()), {'accept': 'image/*'})
     self.assertWidgetRendersTo(f, '<input type="file" name="f" accept="image/*" required id="id_f" />')
Example #2
0
 def test_widget_attrs_accept_specified(self):
     f = ImageField(widget=FileInput(attrs={'accept': 'image/png'}))
     self.assertEqual(f.widget_attrs(f.widget), {})
     self.assertWidgetRendersTo(
         f,
         '<input type="file" name="f" accept="image/png" required id="id_f" />'
     )
Example #3
0
class CustomUserSerializer(serializers.ModelSerializer):

    class Meta:
        model = get_user_model()
        fields = ['id', 'username', 'password1', 'password2',
                  'first_name', 'last_name', 'group', 'restaurant', 'photo', 'qr_code']
        read_only_fields = ('id',)

    photo = ImageField(allow_empty_file=True, required=False)
    qr_code = ImageField(allow_empty_file=True, required=False)

    password1 = serializers.CharField(write_only=True)
    password2 = serializers.CharField(write_only=True)
    group = serializers.CharField()

    def validate(self, data):
        if data['password1'] != data['password2']:
            raise serializers.ValidationError('Passwords must match.')
        return data

    def create(self, validated_data):
        group_data = validated_data.pop('group')
        group, _ = Group.objects.get_or_create(name=group_data)
        data = {
            key: value for key, value in validated_data.items()
            if key not in ('password1', 'password2')
        }
        data['password'] = validated_data['password1']
        user = self.Meta.model.objects.create_user(**data)
        user.groups.add(group)
        user.save()
        return user
 def test_file_extension_validation(self):
     f = ImageField()
     img_path = get_img_path('filepath_test_files/1x1.png')
     with open(img_path, 'rb') as img_file:
         img_data = img_file.read()
     img_file = SimpleUploadedFile('1x1.txt', img_data)
     with self.assertRaisesMessage(ValidationError, "File extension 'txt' is not allowed."):
         f.clean(img_file)
Example #5
0
    def validate(self, attrs):

        default_error_messages = {
            'Image Provided is Invalid':
            'Please Upload a valid image. The file you uploaded was either not an image'
        }

        for i in self.initial_data.getlist('image'):

            django_field = DjangoImageField()
            django_field.error_messages = default_error_messages
            django_field.clean(i)
        return attrs
Example #6
0
    def validate(self, attrs):
    
        default_error_messages = {
            'invalid_image':
            'Upload a valid image. The file you uploaded was either not an image'
        }

        for i in self.initial_data.getlist('image'):
            print('this is imgData', i)
            django_field = DjangoImageField()
            django_field.error_messages = default_error_messages
            django_field.clean(i)
        return attrs
Example #7
0
    def test_imagefield_annotate_with_image_after_clean(self):
        f = ImageField()

        img_path = get_img_path("filepath_test_files/1x1.png")
        with open(img_path, "rb") as img_file:
            img_data = img_file.read()

        img_file = SimpleUploadedFile("1x1.png", img_data)
        img_file.content_type = "text/plain"

        uploaded_file = f.clean(img_file)

        self.assertEqual("PNG", uploaded_file.image.format)
        self.assertEqual("image/png", uploaded_file.content_type)
Example #8
0
    def test_imagefield_annotate_with_image_after_clean(self):
        f = ImageField()

        img_path = get_img_path("filepath_test_files/1x1.png")
        with open(img_path, "rb") as img_file:
            img_data = img_file.read()

        img_file = SimpleUploadedFile("1x1.png", img_data)
        img_file.content_type = "text/plain"

        uploaded_file = f.clean(img_file)

        self.assertEqual("PNG", uploaded_file.image.format)
        self.assertEqual("image/png", uploaded_file.content_type)
Example #9
0
class FaviconsConfig(Form):
    favicon16 = ImageField(allow_empty_file=True,
                           required=False,
                           label=_('Favicon 16px'))
    favicon32 = ImageField(allow_empty_file=True,
                           required=False,
                           label=_('Favicon 32px'))
    favicon96 = ImageField(allow_empty_file=True,
                           required=False,
                           label=_('Favicon 96px'))
    favicon120 = ImageField(allow_empty_file=True,
                            required=False,
                            label=_('Favicon 120px'))
    favicon152 = ImageField(allow_empty_file=True,
                            required=False,
                            label=_('Favicon 152px'))
    favicon167 = ImageField(allow_empty_file=True,
                            required=False,
                            label=_('Favicon 167px'))
    favicon180 = ImageField(allow_empty_file=True,
                            required=False,
                            label=_('Favicon 180px'))
    favicon200 = ImageField(allow_empty_file=True,
                            required=False,
                            label=_('Favicon 200px'))
Example #10
0
    def test_imagefield_annotate_with_image_after_clean(self):
        f = ImageField()

        img_path = get_img_path('filepath_test_files/1x1.png')
        with open(img_path, 'rb') as img_file:
            img_data = img_file.read()

        img_file = SimpleUploadedFile('1x1.png', img_data)
        img_file.content_type = 'text/plain'

        uploaded_file = f.clean(img_file)

        self.assertEqual('PNG', uploaded_file.image.format)
        self.assertEqual('image/png', uploaded_file.content_type)
Example #11
0
    def test_imagefield_annotate_with_image_after_clean(self):
        f = ImageField()

        img_path = get_img_path('filepath_test_files/1x1.png')
        with open(img_path, 'rb') as img_file:
            img_data = img_file.read()

        img_file = SimpleUploadedFile('1x1.png', img_data)
        img_file.content_type = 'text/plain'

        uploaded_file = f.clean(img_file)

        self.assertEqual('PNG', uploaded_file.image.format)
        self.assertEqual('image/png', uploaded_file.content_type)
Example #12
0
class WebsiteForm(forms.ModelForm):
    sidebar = CharField(strip=False, required=False, widget=forms.Textarea)
    footer = CharField(strip=False, required=False, widget=forms.Textarea)
    favicon = ImageField(required=False, widget=ClearableFileInput)
    navbar_logo = ImageField(required=False, widget=ClearableFileInput)

    helper = FormHelper()
    helper.form_class = 'form-horizontal'
    helper.label_class = 'col-lg-2'
    helper.field_class = 'col-lg-8'
    helper.add_input(Submit('submit', _('Submit')))

    class Meta:
        model = Website
        exclude = ['sidebar_processed', 'footer_processed']
Example #13
0
class CodeSchoolForm(forms.Form):
    name = CharField(label='School Name')
    url = CharField(label='School website url')

    fulltime = BooleanField(label='Fulltime available?', required=False)
    hardware = BooleanField(label='Hardware included?', required=False)
    has_online = BooleanField(label='Online Offered?', required=False)
    only_online = BooleanField(label='Online only?', required=False)
    accredited = BooleanField(label='VA Accredited?', required=False)
    housing = BooleanField(label='Housing Included?', required=False)
    mooc = BooleanField(label='MOOC Only?', required=False)

    rep_name = CharField(label='School Representative')
    rep_email = CharField(label='Representative Email')
    address1 = CharField(label='Address Line 1')
    address2 = CharField(label='Address Line 2')
    city = CharField(label='City')
    state = CharField(label='State')
    zipcode = CharField(label='Zipcode')
    country = CharField(label='Country')

    logo = ImageField(label='Logo', validators=[image_validator])

    recaptcha = ReCaptchaField(private_key=settings.RECAPTCHA_PRIVATE_KEY,
                               widget=ReCaptchaWidget())
Example #14
0
class ShopItemForm(forms.ModelForm):
    thumbnail = ImageField(widget=ImagePreviewWidget)
    sale = IntegerField(
        min_value=0,
        max_value=100,
        help_text="Item price reduction (sale) in percent",
    )
    download = forms.FileField()
    try:
        category = TreeNodeChoiceField(
            queryset=CategoryTree.shop.get_parent_leaves("digital"),
            level_indicator="")
    except OperationalError or ProgrammingError:
        pass

    def _post_clean(self):
        if "download" in self.changed_data:
            dl = Download.objects.create(
                file=self.cleaned_data.get("download"))
            dl.save()
        else:
            dl = self.instance.download
        self.cleaned_data["download"] = dl
        super(ShopItemForm, self)._post_clean()

    class Meta:
        model = Item
        fields = "__all__"
Example #15
0
class AuthorForm(ModelForm):
    author_image = ImageField()

    class Meta:
        model = Author
        fields = '__all__'
        widgets = {'user': Select(choices=User.objects.all())}
Example #16
0
class UserExtendForm(ModelForm):
    # 为avatar字段添加校验方法
    avatar = ImageField(required=False, validators=[validate_avatar])

    class Meta:
        model = UserExtend
        fields = ['avatar']
Example #17
0
class GeneralConfig(Form):
    page_title = CharField(max_length=100, label=_('Page name'))
    index_hello = CharField(
        max_length=1000,
        label=_('Index welcome text'),
        help_text=_('This text will be displayed on the home page.'))
    default_page_length = IntegerField(
        max_value=100,
        min_value=10,
        label=_('Default page length'),
        help_text=_('This value affects all paginated sections.'))
    google_analytics = CharField(max_length=200,
                                 label=_('Google analytics ID'),
                                 required=False)
    approval_message = CharField(
        max_length=100,
        label=_('Label of approval'),
        initial='Reviewed',
        help_text=_('This text will be displayed for approved events.'))
    review_pending_explanation = CharField(
        max_length=250, label=_('Pending review explanation'), required=False)
    review_reviewed_explanation = CharField(
        max_length=250, label=_('Reviewed review explanation'), required=False)
    logo_file = ImageField(
        allow_empty_file=True,
        required=False,
        label=_('Your logo'),
        help_text=_('Your logo should have size ratio similar to 370x150px.'))
Example #18
0
class AvatarForm(forms.Form):
    avatar = ImageField(label=_('Avatar'))

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['avatar'].widget.attrs.update({'accept': _('image/*')})
Example #19
0
class DashboardForm(Form):

    image = ImageField(widget=FileInput(attrs={
        'style': 'display: none;',
        'class': 'btn btn-dark',
        'id': 'file'
    }))
Example #20
0
class AppForm(TranslatableModelForm):
    screenshots = ImageField(required=False, widget=ClearableFileInput(attrs={'multiple': True}))
    apks = FileField(required=False, widget=ClearableFileInput(attrs={'multiple': True}))

    def __init__(self, *args, **kwargs):
        super(AppForm, self).__init__(*args, **kwargs)
        if self.instance.category:
            # Show only own and default categories
            self.fields['category'].queryset = Category.objects.filter(
                Q(user=None) | Q(user=self.instance.repo.user))

    def save(self, commit=True):
        # remove old feature graphic if there was one
        if 'feature_graphic' in self.initial and self.initial['feature_graphic'].name \
                and 'feature_graphic' in self.changed_data:
            old_graphic = self.initial['feature_graphic'].path
            if os.path.exists(old_graphic):
                os.remove(old_graphic)
        return super().save(commit)

    class Meta:
        model = App
        fields = ['summary', 'summary_override', 'description', 'description_override',
                  'author_name', 'website', 'category', 'screenshots', 'feature_graphic', 'apks']
        widgets = {'description': MDLTinyMCE(), 'description_override': MDLTinyMCE()}
Example #21
0
class ItemForm(ModelForm):
    name = CharField(
        label='Nombre',
        error_messages=default_error_messages,
        max_length=40,
    )
    description = CharField(
        label='Descripción',
        error_messages=default_error_messages,
        widget=Textarea,
        max_length=140,
        required=False,
    )
    category = CharField(
        label='Categoría',
        error_messages=default_error_messages,
        max_length=40,
    )
    image = ImageField(
        label='Imagen',
        error_messages=default_error_messages,
        required=False,
    )

    class Meta:
        model = Item
        fields = ['name', 'description', 'category', 'image']
Example #22
0
class ChildEditForm(ModelForm):
    """Form for editing/updating child information."""

    # DO
    # maybe no need

    # country_name = CharField(
    #     # lets you get meta data of another model
    #     max_length=Country._meta.get_field('country_name').max_length,)
    image = ImageField(required=False)
    description = CharField(widget=Textarea, required=False)

    class Meta:
        model = Child
        fields = [
            'currently_in_lwb_care', 'date_entered_lwb_care',
            'date_child_left_lwb_care', 'program_number', 'nick_name',
            'given_name_sur', 'given_name_first', 'DOB', 'location_country',
            'education_program', 'image', 'description'
        ]

    def __init__(self, *args, **kwargs):
        """Initialization."""
        username = kwargs.pop('username')

        # # self.fields['child_id'].queryset = Child.objects.filter(child__user__username=username)
        # self.fields['country_name'].initial = Country.objects.get(
        #                                         username=username).country_name
        super().__init__(*args, **kwargs)
        photo = self.instance.photos.first()
        # import pdb; pdb.set_trace()
        if photo:
            self.fields['image'].initial = photo.image
            self.fields['description'].initial = photo.description
Example #23
0
class RegistrationForm(forms.Form):
    login = CharField()
    email = EmailField()
    nick = CharField()
    password = CharField()
    repeat_password = CharField()
    avatar = ImageField(required=False)

    def clean_login(self):
        if len(self.cleaned_data['login']) > 32:
            raise ValidationError(u'Too long login.')
        if Member.objects.filter(username=self.cleaned_data['login']).exists():
            raise ValidationError(u'This login already exists.')
        return self.cleaned_data['login']

    def clean_email(self):
        if Member.objects.filter(email=self.cleaned_data['email']).exists():
            raise ValidationError(u'This email already exists.')
        return self.cleaned_data['email']

    def clean_nick(self):
        if len(self.cleaned_data['nick']) > 32:
            raise ValidationError(u'Too long nick.')
        return self.cleaned_data['nick']

    def clean_repeat_password(self):
        password = self.cleaned_data['password']
        repeat_password = self.cleaned_data['repeat_password']

        if password and password != repeat_password:
            raise ValidationError("Passwords doesn't match.")

        return self.cleaned_data
Example #24
0
class SeguimientoPlanAccionForm(Form):

    resultado_seguimiento = CharField(
        label="Resultado",
        widget=Textarea(attrs={
            'class': 'form-control input-xs',
            'rows': '4',
            'maxlength': '400'
        }),
    )

    fecha_seguimiento = CharField(
        widget=TextInput(attrs={
            'class': 'form-control input-xs',
            'name': 'fecha_seguimiento'
        }), )

    archivo = ImageField(
        label='',
        widget=FileInput(
            attrs={
                'class': 'inputfile',
                'name': 'file-2',
                'data-multiple-caption': '{count} Archivos seleccionados',
                'multiple': '',
                'id': 'id_archivo_seguimiento_plan'
            }),
    )
Example #25
0
class ImageQuickForm(CremeModelForm):
    image = ImageField(label=_('Image file'), max_length=Document._meta.get_field('filedata').max_length)

    class Meta:
        model = Document
        fields = ('user', 'image', 'linked_folder')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        fields = self.fields
        fields['linked_folder'].initial = get_folder_model().objects.filter(uuid=constants.UUID_FOLDER_IMAGES).first()
        # TODO: hook django (create or own widget and set it on ImageField ?)
        fields['image'].widget.attrs = {'accept': ','.join('.' + ext for ext in settings.ALLOWED_IMAGES_EXTENSIONS)}

    def save(self, *args, **kwargs):
        instance = self.instance

        instance.filedata = fpath = handle_uploaded_file(
                self.cleaned_data['image'],
                path=['upload', 'documents'],
                max_length=Document._meta.get_field('filedata').max_length,
            )
        assign_2_charfield(instance, 'title', basename(fpath))

        return super().save(*args, **kwargs)
Example #26
0
class EvidenciaHallazgoForm(Form):

    titulo = CharField(widget=TextInput(
        attrs={
            'class': 'form-control input-xs',
            'maxlength': '40',
            'id': 'id_titulo_evidencia'
        }), )

    observacion = CharField(widget=Textarea(
        attrs={
            'class': 'form-control input-xs',
            'rows': '4',
            'maxlength': '400',
            'id': 'id_observacion_evidencia'
        }), )

    archivo = ImageField(
        label='Recursos Necesarios',
        widget=FileInput(
            attrs={
                'class': 'inputfile',
                'name': 'file-2',
                'data-multiple-caption': '{count} Archivos seleccionados',
                'multiple': '',
                'id': 'id_archivo_evidencia'
            }),
    )
 def get_field(self, page, language, initial=None):
     help_text = ""
     widget = ImageInput(page, language)
     return ImageField(widget=widget,
                       initial=initial,
                       help_text=help_text,
                       required=False)
Example #28
0
class ImageForm(forms.Form):
    MIN_RESOLUTION = (184, 184)
    MAX_RESOLUTION = (1000, 1000)
    MAX_SIZE = 3145728
    image = ImageField(label='Аватарка',
                       required=False,
                       widget=FileInput({
                           'accept': '.png, .jpg',
                           'class': 'input-file',
                           'name': 'file',
                           'id': 'file'
                       }))

    def clean_image(self):
        if self.cleaned_data['image'] is None:
            raise ValidationError('')
        image = self.cleaned_data['image']
        img = Image.open(image)
        min_h, min_w = self.MIN_RESOLUTION
        max_h, max_w = self.MAX_RESOLUTION
        max_size = self.MAX_SIZE
        if image.size > max_size:
            raise ValidationError('Размер изображения не должен превышать 3MB')
        if img.height < min_h or img.width < min_w:
            raise ValidationError(
                'Разрешение изображени должно составлять 184 x 184 пикселя')
        if img.height > max_h or img.width > max_w:
            raise ValidationError(
                'Разрешение изображени не должно превышать 1000 x 1000 пикселей'
            )
        return image
class CompanyForm(Form):
    title = CharField(max_length=50, label='Название компании')
    location = CharField(max_length=50, label='География')
    logo = ImageField(label='Загрузить новый логотип', required=False)
    description = CharField(widget=Textarea(attrs={'rows': 4}),
                            label='Информация о компании')
    employee_count = IntegerField(label='Количество человек в компании')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.add_input(
            Submit('submit', 'Сохранить', css_class='float-right'))

        self.helper.layout = Layout(
            Row(
                Column('title', css_class='form-group col-md-6 mb-0'),
                Column('logo', css_class='form-group col-md-6 mb-0'),
            ),
            Row(
                Column('employee_count', css_class='form-group col-md-6 mb-0'),
                Column('location', css_class='form-group col-md-6 mb-0'),
            ),
            'description',
        )
Example #30
0
class NewsForm(ModelForm):
    title = CharField(max_length=128, required=False)
    text = CharField(max_length=255,
                     required=False,
                     widget=Textarea(attrs={
                         'cols': 30,
                         'rows': 10
                     }))
    attachment = ImageField(label=_('Pic'),
                            required=False,
                            error_messages={'invalid': _("Image files only")},
                            widget=FileInput)
    category = ModelChoiceField(queryset=Category.objects.values_list(
        'name', flat=True).order_by('name'),
                                empty_label=None)

    class Meta:
        model = News
        fields = ['title', 'text', 'attachment', 'category']
        labels = {
            'title': _('Title'),
            'text': _('Text'),
            'category': _('Category'),
            'attachment': _('Attachment')
        }
Example #31
0
class AdImageForm(ModelForm):

    image = ImageField(label=_('Image'))

    class Meta:
        model = AdImage
        fields = ('image',)
Example #32
0
class EditProfileForm(Form):
    username = CharField(max_length=30, required=False)
    first_name = CharField(max_length=50, required=False)
    last_name = CharField(max_length=50, required=False)
    email = EmailField(required=False)
    birthday = DateField(required=False,
                         widget=SelectDateWidget(empty_label=("Choose Year",
                                                              "Choose Month",
                                                              "Choose Day"),
                                                 years=range(1920, 2016)))
    gender = ChoiceField(choices=(('M', 'Male'), ('F', 'Female')),
                         required=False)
    avatar = ImageField(required=False)

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if email and User.objects.filter(email=email).count():
            raise ValidationError('Email already in use!')
        return email

    def clean_username(self):
        username = self.cleaned_data.get('username')
        if username and User.objects.filter(username=username).count():
            raise ValidationError('Username taken, pick another one!')
        return username
Example #33
0
    def test_imagefield_annotate_with_bitmap_image_after_clean(self):
        """
        This also tests the situation when Pillow doesn't detect the MIME type
        of the image (#24948).
        """
        from PIL.BmpImagePlugin import BmpImageFile
        try:
            Image.register_mime(BmpImageFile.format, None)
            f = ImageField()
            img_path = get_img_path('filepath_test_files/1x1.bmp')
            with open(img_path, 'rb') as img_file:
                img_data = img_file.read()

            img_file = SimpleUploadedFile('1x1.bmp', img_data)
            img_file.content_type = 'text/plain'

            uploaded_file = f.clean(img_file)

            self.assertEqual('BMP', uploaded_file.image.format)
            self.assertIsNone(uploaded_file.content_type)
        finally:
            Image.register_mime(BmpImageFile.format, 'image/bmp')