コード例 #1
0
ファイル: forms.py プロジェクト: priestd09/Geotrek
class ImportDatasetFormWithFile(ImportDatasetForm):
    zipfile = forms.FileField(label=_('File'),
                              required=True,
                              widget=forms.FileInput)

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

        self.helper.layout = Layout(
            Div(
                Div(
                    'parser',
                    'zipfile',
                ),
                FormActions(
                    Submit('upload-file',
                           _("Upload"),
                           css_class='button white')),
                css_class='file-attachment-form',
            ))

    def clean_zipfile(self):
        if self.cleaned_data['zipfile'].content_type != "application/zip":
            raise django_forms.ValidationError(_("File must be of ZIP type."),
                                               code='invalid')
コード例 #2
0
ファイル: forms.py プロジェクト: kapilmitttal/moztrap
class BaseCaseVersionForm(forms.Form):
    """Base form class for AddCaseForm and EditCaseVersionForm."""
    name = forms.CharField(max_length=200)
    description = forms.CharField(required=False, widget=mtforms.BareTextarea)

    add_attachment = forms.FileField(required=False)

    def __init__(self, *args, **kwargs):
        """Initialize BaseCaseVersionForm, including StepFormSet."""
        super(BaseCaseVersionForm, self).__init__(*args, **kwargs)

        self.steps_formset = StepFormSet(
            data=self.data or None,
            instance=getattr(self, "instance", None),
        )

    def is_valid(self):
        """The form and the steps formset must both be valid."""
        return self.steps_formset.is_valid() and super(BaseCaseVersionForm,
                                                       self).is_valid()

    def save_attachments(self, caseversion):
        # @@@ convert into a modelmultiplechoicefield widget?
        delete_ids = set(self.data.getlist("remove-attachment"))
        caseversion.attachments.filter(id__in=delete_ids).delete()

        if self.files:  # if no files, it's a plain dict, has no getlist
            for uf in self.files.getlist("add_attachment"):
                model.CaseAttachment.objects.create(
                    attachment=uf,
                    name=uf.name,
                    caseversion=caseversion,
                    user=self.user,
                )
コード例 #3
0
ファイル: forms.py プロジェクト: gutard/Geotrek-admin
class ImportDatasetFormWithFile(ImportDatasetForm):
    zipfile = forms.FileField(label=_('File'),
                              required=True,
                              widget=forms.FileInput)

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

        self.fields['parser'].label = _('Data to import from local file')
        self.helper.layout = Layout(
            Div(
                Div(
                    'parser',
                    'zipfile',
                ),
                FormActions(
                    Submit('upload-file',
                           _("Import"),
                           css_class='button white')),
                css_class='file-attachment-form',
            ))

    def clean_zipfile(self):
        z = self.cleaned_data['zipfile']
        if not is_zipfile(z):
            raise django_forms.ValidationError(_("File must be of ZIP type."),
                                               code='invalid')
        # Reset position for further use.
        z.seek(0)
コード例 #4
0
    def finalize_form(self):
        # Can we change threads states?
        if self.include_thread_weight and (self.request.acl.threads.can_pin_threads(self.forum) and
            (not self.thread or self.request.acl.threads.can_pin_threads(self.forum) >= self.thread.weight)):
            thread_weight = []
            if self.request.acl.threads.can_pin_threads(self.forum) == 2:
                thread_weight.append((2, _("Announcement")))
            thread_weight.append((1, _("Sticky")))
            thread_weight.append((0, _("Standard")))
            if thread_weight:
                try:
                    current_weight = self.thread.weight
                except AttributeError:
                    current_weight = 0
                self.add_field('thread_weight', forms.TypedChoiceField(widget=forms.RadioSelect,
                                                                       choices=thread_weight,
                                                                       required=False,
                                                                       coerce=int,
                                                                       initial=current_weight))

        # Can we lock threads?
        if self.include_close_thread and self.request.acl.threads.can_close(self.forum):
            self.add_field('close_thread', forms.BooleanField(required=False))

        if self.request.acl.threads.can_upload_attachments(self.forum):
            self.add_field('new_file', forms.FileField(required=False))

        # Give inheritor chance to set custom fields
        try:
            type_fields_call = self.type_fields
        except AttributeError:
            type_fields_call = None
        if type_fields_call:
            type_fields_call()
コード例 #5
0
class AllFieldsForm(forms.Form):
    boolean = forms.BooleanField()
    char = forms.CharField(max_length=50)
    choices = forms.ChoiceField(choices=ALPHA_CHOICES)
    date = forms.DateField()
    datetime = forms.DateTimeField()
    decimal = forms.DecimalField(decimal_places=2, max_digits=4)
    email = forms.EmailField()
    file_field = forms.FileField()
    file_path = forms.FilePathField(path='uploads/')
    float_field = forms.FloatField()
    generic_ip_address = forms.GenericIPAddressField()
    image = forms.ImageField()
    integer = forms.IntegerField()
    ip_address = forms.IPAddressField()
    multiple_choices = forms.MultipleChoiceField(choices=ALPHA_CHOICES)
    null_boolean = forms.NullBooleanField()
    regex_field = forms.RegexField(regex='^\w+$', js_regex='^[a-zA-Z]+$')
    slug = forms.SlugField()
    split_datetime = forms.SplitDateTimeField()
    time = forms.TimeField()
    typed_choices = forms.TypedChoiceField(choices=NUMERIC_CHOICES, coerce=int)
    typed_multiple_choices = forms.TypedMultipleChoiceField(
        choices=NUMERIC_CHOICES, coerce=int)
    url = forms.URLField()

    # GIS fields.
    if gis_forms:
        osm_point = gis.PointField(
            widget=mixin(gis.PointWidget, gis.BaseOsmWidget))
        osm_multipoint = gis.MultiPointField(
            widget=mixin(gis.MultiPointWidget, gis.BaseOsmWidget))
        osm_linestring = gis.LineStringField(
            widget=mixin(gis.LineStringWidget, gis.BaseOsmWidget))
        osm_multilinestring = gis.MultiLineStringField(
            widget=mixin(gis.MultiLineStringWidget, gis.BaseOsmWidget))
        osm_polygon = gis.PolygonField(
            widget=mixin(gis.PolygonWidget, gis.BaseOsmWidget))
        osm_multipolygon = gis.MultiPolygonField(
            widget=mixin(gis.MultiPolygonWidget, gis.BaseOsmWidget))

        gmap_point = gis.PointField(
            widget=mixin(gis.PointWidget, BaseGMapWidget))
        gmap_multipoint = gis.MultiPointField(
            widget=mixin(gis.MultiPointWidget, BaseGMapWidget))
        gmap_linestring = gis.LineStringField(
            widget=mixin(gis.LineStringWidget, BaseGMapWidget))
        gmap_multilinestring = gis.MultiLineStringField(
            widget=mixin(gis.MultiLineStringWidget, BaseGMapWidget))
        gmap_polygon = gis.PolygonField(
            widget=mixin(gis.PolygonWidget, BaseGMapWidget))
        gmap_multipolygon = gis.MultiPolygonField(
            widget=mixin(gis.MultiPolygonWidget, BaseGMapWidget))
コード例 #6
0
ファイル: forms.py プロジェクト: oddbird/mlt
class AddressImportForm(forms.Form):
    file = forms.FileField()
    tag = forms.CharField()

    def clean_tag(self):
        tag = self.cleaned_data["tag"]
        if models.AddressBatch.objects.filter(tag=tag).exists():
            raise forms.ValidationError("This batch tag is already used.")
        return tag

    def save(self, user):
        i = CSVAddressImporter(user=user,
                               timestamp=datetime.now(),
                               tag=self.cleaned_data["tag"])

        return i.process_file(self.cleaned_data["file"])
コード例 #7
0
ファイル: forms.py プロジェクト: rogeriofalcone/django-sis
class StudentReportWriterForm(StudentSelectForm):
    template = forms.ModelChoiceField(required=False,
                                      queryset=Template.objects.all())
    upload_template = forms.FileField(
        required=False,
        help_text="You may choose a template or upload one here")

    def clean(self):
        data = super(StudentReportWriterForm, self).clean()
        if not data.get('student') and not data.get('all_students'):
            raise forms.ValidationError(
                "You must either check \"all students\" or select a student")
        if not data.get('template') and not data.get('upload_template'):
            raise forms.ValidationError(
                "You must either select a template or upload one.")
        return data
コード例 #8
0
class DocumentosUploadForm(forms.ModelForm):    
    class Meta:
        model = Documentos
        exclude = ('user','fechaalta')

    def __init__(self, *args, **kwargs):
        prefijo="documentos"
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            TR( Field('id',css_class="control-group hidden",template=campo),
                Field('appcc_id',css_class="control-group hidden",template=campo),
                Field('manautctrl_id',css_class="control-group hidden", template=campo),
                Field('planautoctrl_id',css_class="control-group hidden",template=campo),
                Field('cabreg_id',css_class="control-group hidden",template=campo),
                Field('detreg_id',css_class="control-group hidden",template=campo),
                Field('registros_id',css_class="control-group hidden",template=campo),
                Field('cuadgest_id',css_class="control-group hidden",template=campo),
                Field('relentes_id',css_class="control-group hidden",template=campo),
                Field('gestincid_id',css_class="control-group hidden",template=campo),
                Field('cabanali_id',css_class="control-group hidden",template=campo),
                Field('cabinftec_id',css_class="control-group hidden",template=campo),
                #TD(Field('fecha',css_class="control-group hidden", template="form/field_date_table.html")),
                #TD(Field('denominacion',css_class="control-group", template="form/field.html")),
                #TD(Field('archivos',css_class="control-group", template="form/field.html")),
                #TD(Field('DELETE',template="form/field.html")), 
                css_class="form-row inline %s" % prefijo ) ,#cambiar por el prefijo
 
        )
        super(DocumentosUploadForm, self).__init__(*args, **kwargs)


    id                = forms.IntegerField(required=False)
    appcc_id          = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    manautctrl_id     = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    planautoctrl_id   = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cabreg_id         = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    detreg_id         = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    registros_id      = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cuadgest_id       = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    relentes_id       = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    gestincid_id      = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cabanali_id       = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cabinftec_id      = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    fecha             = forms.DateField(initial=datetime.date.today,required=False)
    denominacion      = forms.CharField(max_length="200",required=False)    
    archivos          = forms.FileField(label='Selecciona un archivo',required=False)
コード例 #9
0
class UploadForm(forms.Form):
    id                = forms.IntegerField(required=False)
    appcc_id          = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    manautctrl_id     = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    planautoctrl_id   = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cabreg_id         = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    detreg_id         = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    registros_id      = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cuadgest_id       = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    relentes_id       = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    gestincid_id      = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cabanali_id       = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cabinftec_id      = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    fecha             = forms.DateField(initial=datetime.date.today,required=False)
    denominacion      = forms.CharField(max_length="200",required=False)    
    archivos          = forms.FileField(label='Selecciona un archivo',required=False)
    contenido         = forms.CharField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
コード例 #10
0
class DetInfTecnicosForms(forms.ModelForm):
    class Meta:
        model = DetInformesTecnicos
        fields = '__all__'
#         widgets = {
#                    'texto':forms.Textarea(attrs={'data-form':'wysihtml5',
#                                                       'style':'width:95%',
#                                                       #'class':'textarea form-control'
#                                                       })
#         }

    def __init__(self, *args, **kwargs):
        super(DetInfTecnicosForms, self).__init__(*args, **kwargs)        
        prefijo="detinftec"
        self.fields['orden'].widget = TextInput(attrs={'class':'numberinput',
                                                       'type':'number',
                                                       'style':'width:35px;'})
        self.fields['texto'].widget = Textarea(attrs={
                                                      'data-form':'wysihtml5',
                                                      'style':'width:95%',
                                                      #'class':'form-row inline %s' % prefijo
                                                      })
        
        #self.fields['texto'].widget = Textarea(attrs={'data-form':'wysihtml5',
        #                                              'style':'width:95%'})
#         self.helper = FormHelper()
#         self.helper.form_tag = False
#         self.helper.layout = Layout(
#             TR( Field('id',css_class="control-group hidden"),
#                 TD(Field('orden',css_class=mini ,template="form/field.html")),
#                 TD(Field('titulo',css_class=xlarge, template="form/field.html")),
#                 TD(Field('texto',template="form/formset_field_textarea.html")),
#                 TD(Field('fileImagen', template="form/field.html")),
#                 #TD(Field('texto')),
#                 TD(Field('DELETE',template="form/field.html")), css_class="form-row inline %s" % prefijo ) ,#cambiar por el prefijo
#  
#         )
        
    id            = forms.IntegerField(required=False)        
    fileImagen = forms.FileField(label="Imagen",required=False)
コード例 #11
0
ファイル: forms.py プロジェクト: oddbird/mlt
class LoadParcelsForm(forms.Form):
    shapefile = forms.FileField()

    def clean_shapefile(self):
        try:
            z = zipfile.ZipFile(self.cleaned_data["shapefile"], 'r')
        except zipfile.BadZipfile:
            raise forms.ValidationError(
                "Uploaded file is not a valid zip file.")

        shapefile_path = None
        target_dir = tempfile.mkdtemp(suffix="-mlt-parcel-shapefile")
        try:
            for name in z.namelist():
                if name.startswith(os.path.sep) or os.path.pardir in name:
                    raise forms.ValidationError(
                        "Zip file contains unsafe paths (absolute or with ..)."
                    )
                z.extract(name, target_dir)
                if name.endswith(".shp"):
                    shapefile_path = os.path.join(target_dir, name)

            if shapefile_path is None:
                raise forms.ValidationError(
                    "Unable to find a .shp file in uploaded zip file.")
        except forms.ValidationError:
            shutil.rmtree(target_dir)
            raise

        self.cleaned_data["target_dir"] = target_dir
        self.cleaned_data["shapefile_path"] = shapefile_path

        return self.cleaned_data["shapefile"]

    def save(self):
        return tasks.load_parcels_task.delay(
            self.cleaned_data["target_dir"],
            self.cleaned_data["shapefile_path"])
コード例 #12
0
class PersonalForms(forms.ModelForm):
    class Meta:
        model = Personal

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_id     = 'id-personal'
        self.helper.form_class  = 'form-horizontal'
        self.helper.form_method = 'post'
        self.helper.form_action = 'submit_survey'
        self.helper.layout = Layout(
            Fieldset(
                Div('id',css_class="control-group hidden"),
                Div( Div( 'dni' ,css_class=s4), Div( 'apellidos',css_class=s4), Div('nombres',css_class=s4),css_class=s12),
                Div( Div('estadocivil',css_class=s4), Div(Field('fechanacimiento',template="form/field_date.html"), css_class=s4, ), Div('sexo', css_class=s4), css_class=s12),
                Div( Div('nss',css_class=s4), Div('cargo',css_class=s4) ,Div('catprofesional',css_class=s4) ,css_class="span12"),
                Div( Div( Field('email'), css_class=s4 ),Div(Field('emailnotifica'),css_class=s4), Div(Field('telefonosms'),css_class=s4),css_class=s12),
                Div(Field('fechabaja',template=fecha,css_class=s6),css_class=s4),
                Div ( Field('observaciones', template=editor), css_class=s12),
                Div('fileImagen',css_class=s12)
            ),
            FormActions( Submit( "Update","Guardar"), Button( "cancel","Cancelar"))
        )
        return super(PersonalForms, self).__init__(*args, **kwargs)
    def save(self, commit=True, user=None,*args, **kwargs):

        self.user      = user
        instance =super(PersonalForms,self).save(commit=False)
        if commit:
            instance.save(user)
        return instance
    id = forms.IntegerField(required=False)
    catprofesional =  AutoCompleteSelectField(lookup_class=TpCatProfesionalLookup ,required=True, label=_("Cat. Profesional"),help_text=_("Autoselección"))
    fileImagen = forms.FileField(label="Firma",required=False)

    id = forms.IntegerField(required=False)
    catprofesional =  AutoCompleteSelectField(lookup_class=TpCatProfesionalLookup ,required=True, label=_("Cat. Profesional"),help_text=_("Autoselección"))
コード例 #13
0
class PostalAttachmentForm(forms.Form, PostalScanMixin):
    scan = forms.FileField(label=_("Scanned Document"),
                           help_text=PostalReplyForm.scan_help_text)
コード例 #14
0
class PostalReplyForm(forms.Form, PostalScanMixin):
    scan_help_text = mark_safe(
        _("Uploaded scans can be PDF, JPG or PNG. Please make sure to <strong>redact/black out all private information concerning you</strong>."
          ))
    date = forms.DateField(
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": _('mm/dd/YYYY')
        }),
        label=_("Send Date"),
        help_text=_("Please give the date the reply was sent."),
        localize=True)
    sender = forms.CharField(
        label=_("Sender Name"),
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": _("Sender Name")
        }),
        required=True)
    subject = forms.CharField(
        label=_("Subject"),
        required=False,
        max_length=230,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": _("Subject")
        }))
    text = forms.CharField(
        label=_("Letter"),
        widget=forms.Textarea(
            attrs={
                "placeholder": _("Letter text you have received"),
                "class": "form-control"
            }),
        required=False,
        help_text=
        _("The text can be left empty, instead you can upload scanned documents."
          ))
    scan = forms.FileField(label=_("Scanned Letter"),
                           required=False,
                           help_text=scan_help_text)
    not_publishable = forms.BooleanField(
        label=_("You are not allowed to publish some received documents"),
        initial=False,
        required=False,
        help_text=
        _('If the reply explicitly states that you are not allowed to publish some of the documents (e.g. due to copyright), check this.'
          ))

    def clean_date(self):
        date = self.cleaned_data['date']
        now = timezone.now().date()
        if date > now:
            raise forms.ValidationError(
                _("Your reply date is in the future, that is not possible."))
        return date

    def clean(self):
        cleaned_data = self.cleaned_data
        text = cleaned_data.get("text")
        scan = cleaned_data.get("scan")
        if not (text or scan):
            raise forms.ValidationError(
                _("You need to provide either the letter text or a scanned document."
                  ))
        return cleaned_data
コード例 #15
0
class AddFeedbackForm(forms.Form):
    content = forms.CharField(max_length=MAX_MESSAGE_INPUT_CHARS,
                              widget=forms.Textarea(attrs={'rows': '3'}))
    feedbabk_type = forms.ChoiceField(choices=Feedback.FEEDBACK_TYPES)

    voice_recording = forms.FileField(required=False)
コード例 #16
0
ファイル: forms.py プロジェクト: rogeriofalcone/django-sis
class UploadFileForm(forms.Form):
    file = forms.FileField()
コード例 #17
0
ファイル: forms.py プロジェクト: rogeriofalcone/django-sis
class StudentGradeReportWriterForm(forms.Form):
    date = forms.DateField(widget=adminwidgets.AdminDateWidget(),
                           initial=date.today,
                           validators=settings.DATE_VALIDATORS)
    template = forms.ModelChoiceField(required=False,
                                      queryset=Template.objects.all())
    upload_template = forms.FileField(
        required=False,
        help_text="You may choose a template or upload one here")
    include_deleted = forms.BooleanField(required=False)
    all_students = forms.BooleanField(
        required=False, widget=forms.CheckboxInput(attrs={'onclick': ''}))
    student = AutoCompleteSelectMultipleField('student', required=False)
    sort_by = forms.ChoiceField(choices=(('last_name', 'Student last name'),
                                         ('year', 'School year'),
                                         ('cohort', 'Primary Cohort')),
                                initial=1)
    filter_year = forms.ModelMultipleChoiceField(
        required=False, queryset=GradeLevel.objects.all())
    filter_cohort = forms.ModelMultipleChoiceField(
        required=False, queryset=Cohort.objects.all())
    omit_substitutions = forms.BooleanField(
        required=False
    )  # benchmark_grade only; displayed conditionally in template

    def clean(self):
        data = super(StudentGradeReportWriterForm, self).clean()
        if not data.get('student') and not data.get('all_students'):
            raise forms.ValidationError(
                "You must either check \"all students\" or select a student")
        if not data.get('template') and not data.get('upload_template'):
            raise forms.ValidationError(
                "You must either select a template or upload one.")
        return data

    def get_students(self, options, worker=False):
        """ Returns all students based on criteria. data should be form.cleaned_data """
        if worker:
            from ecwsp.work_study.models import StudentWorker
            students = StudentWorker.objects.all()
        else:
            students = Student.objects.all()

        # if selecting individual students, don't filter out deleted
        # why? Because it's unintuitive to pick one student, forgot about "include
        # deleted" and hit go to recieve a blank sheet.
        if not options['all_students']:
            students = students.filter(id__in=options['student'])
        elif not options['include_deleted']:
            students = students.filter(is_active=True)

        if options['student'].count == 1:
            data['student'] = options['student'][0]

        if options['sort_by'] == "year":
            students = students.order_by('year', 'last_name', 'first_name')
        elif options['sort_by'] == "hoomroom":
            pass

        if options['filter_year']:
            students = students.filter(year__in=options['filter_year'])

        if options['filter_cohort']:
            students = students.filter(cohorts__in=options['filter_cohort'])

        return students
コード例 #18
0
 class FileForm(forms.Form):
     file_ = forms.FileField()
コード例 #19
0
        class Form(forms.Form):
            file_ = forms.FileField()

            def clean_file_(self):
                raise forms.ValidationError('Some error')
コード例 #20
0
ファイル: forms.py プロジェクト: open-build/TolaWork_Dev
class TicketForm(forms.Form):

    queue = forms.ChoiceField(label=_('Queue'), required=True, choices=())

    title = forms.CharField(
        max_length=100,
        required=True,
        widget=forms.TextInput(attrs={'size': '60'}),
        label=_('Summary of the problem'),
    )

    submitter_email = forms.EmailField(
        required=False,
        label=_('Submitter E-Mail Address'),
        widget=forms.TextInput(attrs={'size': '60'}),
        help_text=_('This e-mail address will receive copies of all public '
                    'updates to this ticket.'),
    )

    error_message = forms.CharField(
        widget=forms.Textarea(attrs={
            'cols': 47,
            'rows': 4
        }),
        label=_('Error Message'),
        required=False,
        help_text=
        _('Was an error message displaced? Please copy and paste this error message here. '
          ),
    )
    body = forms.CharField(
        widget=forms.Textarea(attrs={
            'cols': 47,
            'rows': 15
        }),
        label=_('Description of Issue'),
        required=True,
    )

    assigned_to = forms.ChoiceField(
        choices=(),
        required=False,
        label=_('Case owner'),
        help_text=_('If you select an owner other than yourself, they\'ll be '
                    'e-mailed details of this ticket immediately.'),
    )

    priority = forms.ChoiceField(
        choices=Ticket.PRIORITY_CHOICES,
        required=False,
        initial='3',
        label=_('Priority'),
        help_text=_('Please select a priority carefully. If unsure, leave it '
                    'as \'3\'.'),
    )

    type = forms.ChoiceField(
        choices=Ticket.TICKET_TYPE,
        required=True,
        initial='3',
        label=_('Type of Ticket'),
        help_text=_(
            'Enhancements requests or Bugs/Problems with Tola software.'),
    )

    due_date = forms.DateTimeField(
        widget=extras.SelectDateWidget,
        required=False,
        label=_('Due on'),
    )

    def clean_due_date(self):
        data = self.cleaned_data['due_date']
        #TODO: add Google calendar update hook
        #if not hasattr(self, 'instance') or self.instance.due_date != new_data:
        #    print "you changed!"
        return data

    attachment = forms.FileField(
        required=False,
        label=_('Attach File'),
        help_text=
        _('You can attach a file such as a document or screenshot to this ticket.'
          ),
    )

    def __init__(self, *args, **kwargs):
        """
        Add any custom fields that are defined to the form
        """
        super(TicketForm, self).__init__(*args, **kwargs)
        for field in CustomField.objects.all():
            instanceargs = {
                'label': field.label,
                'help_text': field.help_text,
                'required': field.required,
            }

            self.customfield_to_field(field, instanceargs)

    #Crispy Form Helper to add Bootstrap and layout
    helper = FormHelper()
    helper.form_method = 'post'
    helper.form_class = 'form-horizontal'
    helper.label_class = 'col-sm-2'
    helper.field_class = 'col-sm-6'
    helper.form_error_title = 'Form Errors'
    helper.error_text_inline = True
    helper.help_text_inline = True
    helper.html5_required = True
    helper.form_tag = False

    def save(self, user):
        """
        Writes and returns a Ticket() object
        """

        q = Queue.objects.get(id=int(self.cleaned_data['queue']))

        t = Ticket(
            title=self.cleaned_data['title'],
            submitter_email=self.cleaned_data['submitter_email'],
            created=timezone.now(),
            status=Ticket.OPEN_STATUS,
            queue=q,
            description=self.cleaned_data['body'],
            error=self.cleaned_data['error_message'],
            priority=self.cleaned_data['priority'],
            type=self.cleaned_data['type'],
            due_date=self.cleaned_data['due_date'],
        )

        if self.cleaned_data['assigned_to']:
            try:
                u = User.objects.get(id=self.cleaned_data['assigned_to'])
                t.assigned_to = u
            except User.DoesNotExist:
                t.assigned_to = None
        t.save()

        for field, value in self.cleaned_data.items():
            if field.startswith('custom_'):
                field_name = field.replace('custom_', '', 1)
                customfield = CustomField.objects.get(name=field_name)
                cfv = TicketCustomFieldValue(ticket=t,
                                             field=customfield,
                                             value=value)
                cfv.save()

        f = FollowUp(
            ticket=t,
            title=_('Ticket Opened'),
            date=timezone.now(),
            public=True,
            comment=self.cleaned_data['body'],
            user=user,
        )
        if self.cleaned_data['assigned_to']:
            f.title = _('Ticket Opened & Assigned to %(name)s') % {
                'name': t.get_assigned_to
            }

        f.save()

        files = []
        if self.cleaned_data['attachment']:
            import mimetypes
            file = self.cleaned_data['attachment']
            filename = file.name.replace(' ', '_')
            a = Attachment(
                followup=f,
                filename=filename,
                mime_type=mimetypes.guess_type(filename)[0]
                or 'application/octet-stream',
                size=file.size,
            )
            a.file.save(file.name, file, save=False)
            a.save()

            if file.size < getattr(settings, 'MAX_EMAIL_ATTACHMENT_SIZE',
                                   512000):
                # Only files smaller than 512kb (or as defined in
                # settings.MAX_EMAIL_ATTACHMENT_SIZE) are sent via email.
                try:
                    files.append([a.filename, a.file])
                except NotImplementedError:
                    pass

        context = safe_template_context(t)
        context['comment'] = f.comment

        messages_sent_to = []

        if t.submitter_email:
            send_templated_mail(
                'newticket_submitter',
                context,
                recipients=t.submitter_email,
                sender=q.from_address,
                fail_silently=True,
                files=files,
            )
            messages_sent_to.append(t.submitter_email)

        if t.assigned_to and t.assigned_to != user and t.assigned_to.usersettings.settings.get(
                'email_on_ticket_assign', False
        ) and t.assigned_to.email and t.assigned_to.email not in messages_sent_to:
            send_templated_mail(
                'assigned_owner',
                context,
                recipients=t.assigned_to.email,
                sender=q.from_address,
                fail_silently=True,
                files=files,
            )
            messages_sent_to.append(t.assigned_to.email)

        if q.new_ticket_cc and q.new_ticket_cc not in messages_sent_to:
            send_templated_mail(
                'newticket_cc',
                context,
                recipients=q.new_ticket_cc,
                sender=q.from_address,
                fail_silently=True,
                files=files,
            )
            messages_sent_to.append(q.new_ticket_cc)

        if q.updated_ticket_cc and q.updated_ticket_cc != q.new_ticket_cc and q.updated_ticket_cc not in messages_sent_to:
            send_templated_mail(
                'newticket_cc',
                context,
                recipients=q.updated_ticket_cc,
                sender=q.from_address,
                fail_silently=True,
                files=files,
            )

        return t
コード例 #21
0
ファイル: forms.py プロジェクト: shaib/OpenCommunity
class ImportInvitationsForm(forms.Form):
    csv_file = forms.FileField(required=True)

    def __init__(self, *args, **kwargs):
        super(ImportInvitationsForm, self).__init__(*args, **kwargs)
        self.fields['csv_file'].label = _("Upload CSV file to import")
コード例 #22
0
 class Form(forms.Form):
     file_ = forms.FileField(required=False, widget=MyFileInput)
コード例 #23
0
ファイル: forms.py プロジェクト: open-build/TolaWork_Dev
class PublicTicketForm(forms.Form):
    queue = forms.ChoiceField(label=_('Application'),
                              required=True,
                              choices=())

    title = forms.CharField(
        max_length=100,
        required=True,
        widget=forms.TextInput(),
        label=_('Summary of your request'),
    )

    submitter_email = forms.EmailField(
        required=True,
        label=_('Your E-Mail Address'),
        help_text=_('We will e-mail you when your ticket is updated.'),
    )

    body = forms.CharField(
        widget=forms.Textarea(),
        label=_('Description'),
        required=True,
        help_text=_('Please be as descriptive as possible, including any '
                    'details we may need to address your query.'),
    )

    priority = forms.ChoiceField(
        choices=Ticket.PRIORITY_CHOICES,
        required=True,
        initial='3',
        label=_('Urgency'),
        help_text=_('Please select a priority carefully.'),
    )

    type = forms.ChoiceField(
        choices=Ticket.TICKET_TYPE,
        required=True,
        initial='1',
        label=_('Type of Ticket'),
        help_text=_(
            'Enhancement requests or Bugs/Problems with Tola software.'),
    )

    attachment = forms.FileField(
        required=False,
        label=_('Attach File'),
        help_text=
        _('You can attach a file such as a document or screenshot to this ticket.'
          ),
        max_length=1000,
    )

    def __init__(self, *args, **kwargs):
        """
        Add any custom fields that are defined to the form
        """
        super(PublicTicketForm, self).__init__(*args, **kwargs)
        for field in CustomField.objects.filter(staff_only=False):
            instanceargs = {
                'label': field.label,
                'help_text': field.help_text,
                'required': field.required,
            }

            self.customfield_to_field(field, instanceargs)

    #Crispy Form Helper to add Bootstrap and layout
    helper = FormHelper()
    helper.form_method = 'post'
    helper.form_class = 'form-horizontal'
    helper.label_class = 'col-sm-2'
    helper.field_class = 'col-sm-6'
    helper.form_error_title = 'Form Errors'
    helper.error_text_inline = True
    helper.help_text_inline = True
    helper.html5_required = True
    helper.form_tag = False

    def save(self, user):
        """
        Writes and returns a Ticket() object
        """

        q = Queue.objects.get(id=int(self.cleaned_data['queue']))

        t = Ticket(title=self.cleaned_data['title'],
                   submitter_email=self.cleaned_data['submitter_email'],
                   created=timezone.now(),
                   status=Ticket.OPEN_STATUS,
                   queue=q,
                   description=self.cleaned_data['body'],
                   priority=self.cleaned_data['priority'],
                   type=self.cleaned_data['type'])

        t.save()

        for field, value in self.cleaned_data.items():
            if field.startswith('custom_'):
                field_name = field.replace('custom_', '', 1)
                customfield = CustomField.objects.get(name=field_name)
                cfv = TicketCustomFieldValue(ticket=t,
                                             field=customfield,
                                             value=value)
                cfv.save()

        f = FollowUp(
            ticket=t,
            title=_('Ticket Opened Via Web'),
            date=timezone.now(),
            public=True,
            comment=self.cleaned_data['body'],
        )

        f.save()

        files = []
        if self.cleaned_data['attachment']:
            import mimetypes
            file = self.cleaned_data['attachment']
            filename = file.name.replace(' ', '_')
            a = Attachment(
                followup=f,
                filename=filename,
                mime_type=mimetypes.guess_type(filename)[0]
                or 'application/octet-stream',
                size=file.size,
            )
            a.file.save(file.name, file, save=False)
            a.save()

            if file.size < getattr(settings, 'MAX_EMAIL_ATTACHMENT_SIZE',
                                   512000):
                # Only files smaller than 512kb (or as defined in
                # settings.MAX_EMAIL_ATTACHMENT_SIZE) are sent via email.
                files.append([a.filename, a.file])

        context = safe_template_context(t)

        messages_sent_to = []

        send_templated_mail(
            'newticket_submitter',
            context,
            recipients=t.submitter_email,
            sender=q.from_address,
            fail_silently=True,
            files=files,
        )
        messages_sent_to.append(t.submitter_email)

        if q.new_ticket_cc and q.new_ticket_cc not in messages_sent_to:
            send_templated_mail(
                'newticket_cc',
                context,
                recipients=q.new_ticket_cc,
                sender=q.from_address,
                fail_silently=True,
                files=files,
            )
            messages_sent_to.append(q.new_ticket_cc)

        if q.updated_ticket_cc and q.updated_ticket_cc != q.new_ticket_cc and q.updated_ticket_cc not in messages_sent_to:
            send_templated_mail(
                'newticket_cc',
                context,
                recipients=q.updated_ticket_cc,
                sender=q.from_address,
                fail_silently=True,
                files=files,
            )

        return t
コード例 #24
0
 class FileForm(forms.Form):
     file_ = forms.FileField(required=False)