示例#1
0
class SubmissionForm(ModelForm):
    checkpoints_file = forms.FileField()
    test_program_file = forms.FileField()
    class Meta:
        model = Submission
        fields = ('name','description','allow_comments')
        # fields = '__all__'

    def __init__(self,environment, user, *args, **kwargs):
        self.owner = user
        self.environment = environment
        super(SubmissionForm, self).__init__(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.instance.owner = self.owner
        self.instance.environment = self.environment
        self.instance.score = self.score
        self.instance.sub_date = self.sub_date
        super(SubmissionForm, self).save(*args, **kwargs)

    def add_socre(self,score):
        self.score = score

    def add_time(self,sub_date):
        self.sub_date = sub_date
示例#2
0
class SignalForm(forms.Form):
    wav_file = forms.FileField(label='wav file',
                               required=True,
                               widget=ClearableFileInput(attrs={
                                   'style': 'display:none;',
                                   'class': 'wav_file'
                               }))
示例#3
0
文件: forms.py 项目: nearKim/Caffein2
class CoffeeMeetingFeedForm(ModelForm):
    class Meta:
        model = CoffeeMeetingFeed
        fields = ['content', 'coffee_meeting']

    images = forms.FileField(widget=ClearableFileInput(attrs={'multiple': True}), label='커모 후기 사진')

    def __init__(self, *args, **kwargs):
        self.author = kwargs.pop('author', None)
        self.coffee_meeting = kwargs.pop('coffee_meeting', None)
        self.participants = kwargs.pop('participants', None)
        # 업데이트시 participants를 추가해준다.
        if self.participants is None:
            self.participants = kwargs['instance'].coffee_meeting.list_participants()
        super(CoffeeMeetingFeedForm, self).__init__(*args, **kwargs)
        # 커모는 바꾸면 안되겠지
        self.fields['coffee_meeting'].initial = self.coffee_meeting
        self.fields['coffee_meeting'].widget.attrs['readonly'] = True
        self.fields['participants'] = MultipleChoiceField(label='참가자',
                                                          help_text='참가하지 못한 사람은 꼭 <b>체크를 해제</b>해주세요!',
                                                          choices=[(participant.pk, participant) for participant in self.participants],
                                                          initial=[participant.pk for participant in self.participants],
                                                          widget=CheckboxSelectMultiple)

    def clean_coffee_meeting(self):
        # 항상 넘어온 커모를 리턴한다
        return self.coffee_meeting

    def save(self, commit=True):
        instance = super(CoffeeMeetingFeedForm, self).save(commit=False)
        instance.author = self.author
        instance.save()
        return instance
示例#4
0
class AgreementDetailForm(ModelForm):
    evidence = forms.FileField(required=False)

    date_start = forms.Field(widget=DateInputWidget, label=_('start date'))
    date_until = forms.Field(widget=DateInputWidget, label=_('end date'))

    class Meta:
        model = AgreementDetail
        fields = [
            'description', 'date_start', 'date_until', 'state', 'evidence',
            'owner'
        ]
        # widgets = {
        #     'date_start': DateInputWidget
        # 'date_start': DateInput(attrs={'type': 'date'}, format='%m-%d-%Y')
        # }

    def __init__(self, *args, **kwargs):
        super(AgreementDetailForm, self).__init__(*args, **kwargs)
        # _instance = kwargs.pop('instance', None)
        # self.fields['description'].widget.attrs['class'] = 'form-control'
        # self.fields['date_until'].widget.attrs['class'] = 'form-control input-datepicker'
        # self.fields['date_start'].widget.attrs['class'] = 'form-control input-datepicker'
        # self.fields['state'].widget.attrs['class'] = 'form-control'
        # self.fields['evidence'].widget.attrs['class'] = 'form-control'
        add_form_control_class(self.fields)
示例#5
0
class FileUploadAvatarForm(AvatarServiceConfigForm):
    """The UploadAvatarService configuration form."""

    avatar_service_id = 'file-upload'

    js_view_class = 'Djblets.Avatars.FileUploadSettingsFormView'
    template_name = 'avatars/services/file_upload_form.html'

    avatar_upload = forms.FileField(label=_('File'), required=True)

    MAX_FILE_SIZE = 1 * 1024 * 1024
    is_multipart = True

    def clean_file(self):
        """Ensure the uploaded file is an image of an appropriate size.

        Returns:
            django.core.files.UploadedFile:
            The uploaded file, if it is valid.

        Raises:
            django.core.exceptions.ValidationError:
                Raised if the file is too large or the incorrect MIME type.
        """
        f = self.cleaned_data['avatar_upload']

        if f.size > self.MAX_FILE_SIZE:
            raise ValidationError(_('The file is too large.'))

        content_type = f.content_type.split('/')[0]

        if content_type != 'image':
            raise ValidationError(_('Only images are supported.'))

        return f

    def save(self):
        """Save the file and return the configuration.

        Returns:
            dict:
            The avatar service configuration.
        """
        storage = DefaultStorage()

        file_path = self.cleaned_data['avatar_upload'].name
        file_path = storage.get_valid_name(file_path)
        file_data = self.cleaned_data['avatar_upload'].read()

        with storage.open(file_path, 'wb') as f:
            f.write(file_data)

        file_hash = md5()
        file_hash.update(file_data)

        return {
            'absolute_url': storage.url(file_path),
            'file_path': file_path,
            'file_hash': file_hash.hexdigest(),
        }
示例#6
0
class ExcelUploadForm(forms.Form):

    helper = FormHelper()
    helper.label_class = 'col-sm-3'
    helper.field_class = 'col-sm-9'
    helper.form_tag = False
    helper.form_show_errors = True

    excel_upload = forms.FileField(
        label='Excel file.',
        allow_empty_file=False,
        required=True,
        help_text='submit here a bank statement of contributions',
        widget=FileInput(
            attrs={
                'accept':
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel'
            }),
        validators=[
            FileValidator(
                max_size=FILE_UPLOAD_MAX_MEMORY_SIZE,
                allowed_extensions=['xls', 'xlsx'],
                allowed_mimetypes=[
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    'application/vnd.ms-excel',
                    'application/vnd.ms-office',
                ],
                min_size=1)
        ])

    helper.layout = Layout(
        Field('excel_upload', css_class='input-sm form-control'),
        Hidden(name='identity', value=True, css_class='input-sm'),
    )
示例#7
0
class InstagramForm(ModelForm):
    class Meta:
        model = Instagram
        fields = ['content']

    # 여러개의 FileInput을 허용하는 새로운 'images'필드를 정의한다.
    images = forms.FileField(
        widget=ClearableFileInput(attrs={'multiple': True}), label='사진')
示例#8
0
class Add(forms.Form):
    Username = forms.CharField(label='Your name', max_length=100,initial=" ")
    Password=forms.CharField(widget=forms.PasswordInput,label="Password",initial=" ")
    Email = forms.EmailField(label="Email Id:", initial="",)
    age=forms.IntegerField(label="Your age")
    Description=forms.CharField(label="Describe Yourself",widget=forms.Textarea)
    
    Profile_Picture = forms.FileField(label="Your Profile Picture:")
class CsvImportForm(forms.Form):
    """
    Form used by ModelAdminCsvImport
    """
    csv_file = forms.FileField()
    csv_file.label = 'CSV file'
    # csv_file.help_text = 'list of column names or something helpful'
    csv_file.required = True
示例#10
0
class ScanUploadForm(ModelForm, forms.Form):
    file = forms.FileField(required=False, label="Scan in CSV format")
    site = forms.CharField(required=True,
                           label="Site Name that the Scan is based off of")

    class Meta:
        model = Scan
        fields = ['name']
        labels = {'name': ('Scan Name')}
示例#11
0
class ImporterForm(forms.Form):
    file = forms.FileField()

    def clean_file(self):
        f = self.cleaned_data['file']
        peoples = Importer().from_csv(f)
        if len(peoples) == 0:
            raise forms.ValidationError(u'Invalid file')

        return f
示例#12
0
class SolutionForm(forms.Form):
    solution = forms.CharField()
    profile_pic = forms.FileField(required=False)

    def getTask(self):
        return Task1.objects.get(id=self.prefix)

    def getVar(self):
        tasks = list(Task1.objects.filter(number=self.prefix))
        return random.choice(tasks) if tasks else None
示例#13
0
文件: forms.py 项目: nearKim/Caffein2
class PartnerMeetingForm(ModelForm):
    class Meta:
        model = PartnerMeeting
        fields = ['content', 'num_coffee', 'num_eat']

    images = forms.FileField(widget=ClearableFileInput(attrs={'multiple': True}), label='짝모 사진')

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        self.participants = kwargs.pop('participants', None)
        # 업데이트시 participants를 추가해준다.
        if self.participants is None:
            self.participants = kwargs['instance'].partner.containing_active_users()
        super(PartnerMeetingForm, self).__init__(*args, **kwargs)
        self.fields['participants'] = MultipleChoiceField(label='참가자',
                                                          choices=[(participant.user.pk, participant.user) for participant in
                                                                   self.participants],
                                                          widget=CheckboxSelectMultiple)

    def save(self, commit=True):
        instance = super(PartnerMeetingForm, self).save(commit=False)
        instance.partner = Partner.related_partner_user(self.request.user)
        instance.author = self.request.user
        instance.save()
        return instance

    def clean(self):
        cleaned_data = super().clean()
        latest_os = OperationScheme.latest()
        partner = Partner.related_partner_activeuser(ActiveUser.objects.get(user=self.request.user,
                                                                            active_year=latest_os.current_year,
                                                                            active_semester=latest_os.current_semester))
        participants = cleaned_data.get('participants')
        # 커피와 식사 모두 0인 경우
        if cleaned_data.get('num_coffee') == 0 and cleaned_data.get('num_eat') == 0:
            raise forms.ValidationError('\'커모 횟수\'와 \'밥모 횟수\' 모두 0일 수 없습니다.')
        # 커모 수가 음수일 경우
        elif cleaned_data.get('num_coffee') < 0:
            raise forms.ValidationError('\'커모 횟수\'가 음수일 수 없습니다.')
        # 밥모 수가 음수일 경우
        elif cleaned_data.get('num_eat') < 0:
            raise forms.ValidationError('\'밥모 횟수\'가 음수일 수 없습니다.')
        # 아무도 선택하지 않았을때
        elif participants is None:
            raise forms.ValidationError('짝모에 참가한 사람을 선택해주세요.')
        # 위짝지가 없으면 에러 발생
        elif str(partner.up_partner.user.pk) not in participants:
            raise forms.ValidationError('짝모에는 위짝지가 반드시 포함되어야 합니다.')
        # 아래짝지가 없어도 에러 발생
        elif len(participants) == 1:
            raise forms.ValidationError('짝모에는 아래짝지가 반드시 포함되어야 합니다.')
示例#14
0
class CrearNuevoPlanForm(forms.Form):
    nombre_plan = CharField(label="Nombre del Plan",
                            help_text="Nombre del plan a crear.")

    carrera_plan = ChoiceField(label=u'Carrera')
    plan_utilizar = ChoiceField(label=u"Plan a utilizar")

    ## Dice si se va a crear el plan usando el plan base de la carrera
    construir_usando_pb = BooleanField(required=False)

    ## El periodo - año de inicio indica:
    # Cuando el usuario crea un plan vacio- se le agrega un periodo por default con estos datos iniciales
    # Cuando se utiliza como base el plan de estudio de la carrera se comienza el llenado desde este periodo
    # periodo_inicio = ChoiceField(label=u'Periodo inicio')
    anyo_inicio = ChoiceField(label=u"Año inicio")

    archivo_html_expediente = forms.FileField(
        required=False,
        help_text="Archivo HTML de la página expediente.usb.ve.")

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(CrearNuevoPlanForm, self).__init__(*args, **kwargs)

        carreras_bd = CarreraUsb.objects.all()
        self.fields['carrera_plan'].choices = [(c.pk, c.nombre)
                                               for c in carreras_bd]

        get_nombre_tp = Pensum.get_nombre_tipo_plan
        self.fields['plan_utilizar'].choices = [
            (pu.tipo, get_nombre_tp(pu))
            for pu in Pensum.objects.filter(carrera=carreras_bd.first())
        ]

        # self.fields['periodo_inicio'].choices = [(p[0],p[1]) for p in    TrimestrePlaneado.PERIODOS_USB[:-1]]
        self.fields['anyo_inicio'].choices = [(anyo, anyo)
                                              for anyo in range(1990, 2020)]

        self.fields['anyo_inicio'].value = datetime.datetime.now().year

        if self.user != None:
            if self.user.usbid:
                anyo_carnet = int(self.user.usbid[:2])
                if anyo_carnet >= 0 and anyo_carnet <= 90:
                    self.fields['anyo_inicio'].value = int("{0}{1}".format(
                        20, anyo_carnet))
                else:
                    self.fields['anyo_inicio'].value = int("{0}{1}".format(
                        19, anyo_carnet))

        self.fields['construir_usando_pb'].initial = True
示例#15
0
class UploadObjectForm(forms.Form):
    """
    docs: https://github.com/amlyj/horizon/blob/master/openstack_dashboard/api/rest/swift.py

    使用方法:
        form = UploadObjectForm(request.POST, request.FILES)
        if not form.is_valid():
            print '数据不能为空'
        data = form.clean()
        object_file = data['file']
        print 'file_name: %s' % object_file.name
        print 'file_size: %s' % object_file.size
    """
    file = forms.FileField(required=False)
示例#16
0
class MultiUploadForm(forms.Form):
    file = forms.FileField()

    def __init__(self, *args, **kwargs):
        multiuploader_settings = getattr(settings,
                                         "MULTIUPLOADER_FORMS_SETTINGS",
                                         DEFAULTS.MULTIUPLOADER_FORMS_SETTINGS)
        form_type = kwargs.pop("form_type", "default")

        options = {
            'maxFileSize':
            multiuploader_settings[form_type]["MAX_FILE_SIZE"],
            'acceptFileTypes':
            format_file_extensions(
                multiuploader_settings[form_type]["FILE_TYPES"]),
            'maxNumberOfFiles':
            multiuploader_settings[form_type]["MAX_FILE_NUMBER"],
            'allowedContentTypes':
            map(str.lower, multiuploader_settings[form_type]["CONTENT_TYPES"]),
            'autoUpload':
            multiuploader_settings[form_type]["AUTO_UPLOAD"]
        }

        self._options = options
        self.options = json.dumps(options)

        super().__init__(*args, **kwargs)

        self.fields["file"].widget = forms.FileInput(attrs={'multiple': True})

    def clean_file(self):
        content = self.cleaned_data[u'file']

        filename_extension = os.path.splitext(content.name)

        if re.match(self._options['acceptFileTypes'],
                    filename_extension,
                    flags=re.I) is None:
            raise forms.ValidationError('acceptFileTypes')

        content_type = magic.from_buffer(content.read(1024), mime=True)

        if content_type.lower() in self._options['allowedContentTypes']:
            if content._size > self._options['maxFileSize']:
                raise forms.ValidationError("maxFileSize")
        else:
            raise forms.ValidationError("acceptFileTypes")

        return content
示例#17
0
class AddProductView(LoginRequiredMixin, CreateView):
    model = Item
    template_name = 'addProduct.html'
    image = forms.FileField(required=False)
    fields = ('itemName', 'category', 'itemImage', 'itemAvaialable',
              'costPerItem', 'itemDescription')
    login_url = '/users/login/'

    def form_valid(self, form):
        form.is_valid()
        form.instance.itemOwner = self.request.user
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('RentalApp:my_products')
示例#18
0
class SuccessStoriesForm(ModelForm):
    image = forms.FileField(label='Select a file',
                            help_text='max. 42 megabytes')

    class Meta:
        model = SuccessStories
        widgets = {
            'content':
            forms.Textarea(attrs={
                "rows": 10,
                'cols': 40,
                "id": "content-editor"
            })
        }
        exclude = []
class FacebookChatForm(forms.Form):
    chat_file = forms.FileField(widget=FileInput(
        attrs={
            'onchange': 'file = true;',
            'multiple': 'multiple'
        }))

    def clean_chat_file(self):
        data = self.cleaned_data.get("chat_file")

        if data.content_type == "application/json":
            return data
        else:
            raise forms.ValidationError(
                "Your file is not JSON file. Let's try with another file.")
class VideoForm(ModelForm):
    archivo = forms.FileField(validators=[
        FileExtensionValidator(
            ["mp4", "avi", "mpeg", "mov", "wmv", "flv", "divx", "mkv"])
    ])

    def __init__(self, *args, **kwargs):
        super(VideoForm, self).__init__(*args, **kwargs)
        self.fields['nombre'].required = True
        self.fields['nombre'].max_length = 50
        self.fields[
            'nombre'].help_text = "Este nombre será mostrado a los demás usuarios"
        self.fields['nombre'].error_messages = {
            'required': "Este campo es requerido"
        }
        self.fields['descripcion'].required = False
        self.fields['descripcion'].max_length = 50
        self.fields[
            'descripcion'].help_text = "No es necesario que la pongas :v"
        self.fields[
            'thumbnail'].help_text = "Si no escoges un thumbnail el sistema escogerá uno que forme parte de tu vídeo"
        self.fields['thumbnail'].required = False

    class Meta:
        """Meta definition for Videoform."""
        model = Video
        fields = ('nombre', 'descripcion', 'archivo', 'thumbnail')
        widgets = {
            'nombre':
            TextInput(attrs={
                'placeholder': 'El Nombre de tu vídeo',
                'novalidate': ''
            }),
            'descripcion':
            Textarea(attrs={
                'placeholder': 'Agrega una breve descripción del vídeo'
            }),
            'archivo':
            FileInput(attrs={
                'class': 'inputfile-1',
                'accept': "video/*"
            }),
            'thumbnail':
            FileInput(attrs={
                'class': 'inputfile-1',
                'accept': "image/*"
            }),
        }
示例#21
0
class PostForm(forms.Form):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault(
            'label_suffix',
            '')  # globally override the Django >=1.6 default of ':'
        super(PostForm, self).__init__(*args, **kwargs)

    """Post Form"""
    Post = forms.CharField(widget=forms.Textarea(
        attrs={
            "placeholder": "What's going on? Mesmerise us.",
            "rows": "1",
            "cols": "50",
            "autocomplete": "on"
        }))
    Pic = forms.FileField(required=False, label="📷 ")
示例#22
0
class UploadRecords(Form):
    employees_data = forms.FileField()

    def clean_employees_data(self):
        wb = xlrd.open_workbook(
            file_contents=self.cleaned_data['employees_data'].read())
        ws = wb.sheet_by_index(0)
        if ws.nrows == 0:
            raise Exception('Unable to process empty sheet')
        rows = []
        for row_idx in range(ws.nrows):
            row = []
            for col_idx in range(ws.ncols):
                cell = ws.cell(row_idx, col_idx)
                cell_value = cell.value
                if cell.ctype == 2:  # float. convert to str
                    cell_value = str(int(cell.value))
                row.append(cell_value)
            rows.append(row)
        try:
            data = extract_data(rows, wb.datemode)
        except Exception:
            raise forms.ValidationError('o fail ma ni')
        return data

    def save(self):
        data = self.cleaned_data['employees_data']

        for d in data:
            Employee.objects.update_or_create(p_number=d['p_number'],
                                              defaults={
                                                  "initials": d['initials'],
                                                  "last_name": d['last_name'],
                                                  "speciality":
                                                  d['speciality'],
                                                  "t_comm": d['t_comm'],
                                                  "rank": d['rank'],
                                                  "unit": d['dept'],
                                                  "state_of_origin":
                                                  d['state'],
                                                  "phone": d['phone'],
                                                  "date_tos": d['date_tos'],
                                                  "seniority": d['seniority'],
                                                  "remarks": d['remarks']
                                              })

        return
示例#23
0
class SignUp(forms.Form):
    """ Sign Up """
    Name = forms.CharField(
        label="Your Name",
        widget=forms.TextInput(attrs={"placeholder": "It's Nice to meet you"}))
    username = forms.CharField(
        max_length=255,
        widget=forms.TextInput(attrs={"placeholder": "Make it Creative"}))
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={"placeholder": "We wont sell it. "}),
        label="Password")
    email = forms.EmailField(label="Email Id")
    DateOfBirth = forms.DateField(label="Date of Birth")

    Bio = forms.CharField(widget=forms.Textarea(
        attrs={"placeholder": "Tell us about yourself"}))
    profilePic = forms.FileField()
示例#24
0
class CafeCreateUpdateForm(ModelForm):
    class Meta:
        model = Cafe
        fields = ['name', 'address', 'description', 'phone', 'machine', 'grinder', 'price', 'from_time', 'to_time',
                  'closed_day', 'closed_holiday', 'link', 'road_address', 'mapx', 'mapy']
        widgets = {'from_time': TimeInput(attrs={'id':'inline_timepicker_1'}, format="%I:%M %p"),
                   'to_time': TimeInput(attrs={'id':'inline_timepicker_2'}, format="%I:%M %p")}

    images = forms.FileField(required=False, widget=ClearableFileInput(attrs={'multiple': True}))

    def __init__(self, *args, **kwargs):
        super(CafeCreateUpdateForm, self).__init__(*args, **kwargs)
        # Javascript에서 dynamic하게 업데이트 해야 한다
        self.fields['road_address'].widget = HiddenInput()
        self.fields['mapx'].widget = HiddenInput()
        self.fields['mapy'].widget = HiddenInput()
        self.fields['from_time'].input_formats = ["%I:%M %p"]
        self.fields['to_time'].input_formats = ["%I:%M %p"]
示例#25
0
class SpeakerForm(ModelForm):
    class Meta:
        model = Speaker
        fields = (
            'contact_name',
            'contact_email',
            'salutation',
            'first_name',
            'last_name',
            'title',
            'org',
            'zip',
            'email',
            'phone',
            'url',
            'bio',
        )

    photo_upload = forms.FileField(required=False)
示例#26
0
class MatchForm(forms.Form):
    match_json_file = forms.FileField(
        label='Match data in JSON format',
        required=True,
        widget=ClearableFileInput(
            attrs={
                'class': 'form-control-file',
                'accept': '.json,application/json',
                'multiple': True
            }))

    def clean_match_json_file(self):
        match_json_file_list = self.files.getlist('match_json_file')
        match_json_list = list(
            map(lambda file: json.load(file.open('r')), match_json_file_list))

        for match_json in match_json_list:
            match_json_validator(match_json)

        return match_json_list
示例#27
0
class Add(forms.Form):
    Username = forms.CharField(label='Your name', max_length=100, initial=" ")
    Password = forms.CharField(widget=forms.PasswordInput,
                               label="Password",
                               initial=" ")
    Email = forms.EmailField(
        label="Email Id:",
        initial="",
    )
    age = forms.IntegerField(label="Your age")
    Description = forms.CharField(label="Describe Yourself",
                                  widget=forms.Textarea)
    OPTIONS = (("Java", "Java"), ("C++", "C++"), ("C", "C"),
               ("Python", "Python"), ("JavaScript", "JavaScript"), ("Ruby",
                                                                    "Ruby"))
    Languages = forms.MultipleChoiceField(
        required=True,
        widget=forms.CheckboxSelectMultiple,
        choices=OPTIONS,
    )
    Profile_Picture = forms.FileField(label="Your Profile Picture:")
示例#28
0
class OfficialMeetingForm(ModelForm):
    class Meta:
        model = OfficialMeeting
        fields = ['title', 'content', 'category', 'location', 'meeting_date', 'max_participants', 'mapx', 'mapy']
        widgets = {'meeting_date': DateTimeInput(attrs={'id': 'inline_datetimepicker'})}

    images = forms.FileField(widget=ClearableFileInput(attrs={'multiple': True}), label='사진',
                             help_text='모임 관련 사진들이 있다면 첨부해주세요.', required=False)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(OfficialMeetingForm, self).__init__(*args, **kwargs)
        self.fields['meeting_date'].input_formats = ["%Y-%m-%d %I:%M %p"]
        self.fields['mapx'].widget = HiddenInput()
        self.fields['mapy'].widget = HiddenInput()

    def save(self, commit=True):
        instance = super(OfficialMeetingForm, self).save(commit=False)
        instance.author = self.request.user
        instance.save()

        return instance
示例#29
0
class PDFForm(forms.Form):
    pdf_file = forms.FileField()

    pdf_file.widget.attrs.update({
        'class': 'file-upload-input w3-hide',
        'id': 'pdf_file',
        'onchange': 'readURL(this);',
        'accept': 'application/pdf'
    })

    def clean_pdf_file(self, *args, **kwargs):
        pdf = self.cleaned_data.get('pdf_file')
        print('PDF=> ', pdf)
        kind = filetype.guess(pdf)
        print('file type =>', kind.mime)
        print('file extension =>', kind.extension)
        if not pdf:
            raise ValidationError(_('Please select a file'))

        if kind.mime != 'application/pdf':
            raise ValidationError(_('Please select a valid PDF file'))

        return pdf
示例#30
0
class UploadPassRecords(Form):
    pass_data = forms.FileField()

    def clean_pass_data(self):
        wb = xlrd.open_workbook(
            file_contents=self.cleaned_data['pass_data'].read())
        ws = wb.sheet_by_index(0)
        if ws.nrows == 0:
            raise Exception('Unable to process empty sheet')
        rows = []
        for row_idx in range(ws.nrows):
            row = []
            for col_idx in range(ws.ncols):
                cell = ws.cell(row_idx, col_idx)
                cell_value = cell.value
                if cell.ctype == 2:  # float. convert to str
                    cell_value = str(int(cell.value))
                row.append(cell_value)
            rows.append(row)
        try:
            data = extract_pass_data(rows, wb.datemode)
        except Exception:
            raise forms.ValidationError('o fail ma ni')
        return data

    def save(self):
        data = self.cleaned_data['pass_data']
        for d in data:
            emp = Employee.objects.get(p_number=d['p_number'])
            Pass.objects.create(employee=emp,
                                description=d['description'],
                                start=d['start_date'],
                                end=d['end_date'],
                                remarks=d['remarks'])

        return