Ejemplo n.º 1
0
 def use_hidden_widget_for_one2one(self, db_field, kwargs):
     ''' OneToOne fields are rendered with a HiddenInput instead of a select. '''
     if isinstance(db_field, related.OneToOneField):
         attrs = {'id':'id_{}'.format(db_field.name)}
         if db_field.rel:
             _instance = db_field.rel.to()
             if _instance.id:
                 attrs['value'] = _instance.id
         widget = HiddenInput(attrs=attrs)
         # But don't treat it as a hidden widget, e.g. in tabular inlines:
         widget.is_hidden = False
         kwargs['widget'] = widget
Ejemplo n.º 2
0
    def create_hidden(self, name, field, val):
        """
        Creates HTML for a hidden input field.
        """
        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = 'id_%s' % name

        local_attrs = self.build_attrs(id=field % id_)

        h = HiddenInput()
        hidden_html = h.render(field % name, val, local_attrs)

        return hidden_html
Ejemplo n.º 3
0
 def __init__(self, *args, **kwargs):
     self.value = kwargs['value']
     del kwargs['value']
     if 'choices' in kwargs:
         if kwargs['choices'] is not None:
             self.choices = kwargs['choices']
         else:
             self.choices = ()
         del kwargs['choices']
     else:
         self.choices = ()
     super(StaticWidget, self).__init__(*args, **kwargs)
     self.inner = HiddenInput()
Ejemplo n.º 4
0
class StaticWidget(Widget):
    """Widget that just displays and supplies a specific value.

    Useful for "freezing" form fields --- displaying them, but not
    allowing editing.
    """

    def __init__(self, *args, **kwargs):
        self.value = kwargs['value']
        del kwargs['value']
        if 'choices' in kwargs:
            if kwargs['choices'] is not None:
                self.choices = kwargs['choices']
            else:
                self.choices = ()
            del kwargs['choices']
        else:
            self.choices = ()
        super(StaticWidget, self).__init__(*args, **kwargs)
        self.inner = HiddenInput()

    def value_from_datadict(self, data, files, name, ):
        for choice_value, choice_label in self.choices:
            if choice_label == unicode(self.value):
                return choice_value
        return self.value

    def render(self, name, value, attrs=None, choices=(), ):
        if value is None:
            value = ''
        label = value
        the_choices = chain(self.choices, choices)
        for choice_value, choice_label in the_choices:
            if choice_value == value:
                label = choice_label
        # We have this inner hidden widget because that allows us to nicely
        # handle a transition from StaticWidget to another widget type
        # (e.g., the user loads a form while unauthenticated and submits while
        # authenticated)
        hidden_render = self.inner.render(name, value, attrs=attrs)
        return mark_safe(conditional_escape(label) + hidden_render)

    @classmethod
    def replace_widget(cls, formfield, value):
        choices = None
        choices = getattr(formfield.widget, 'choices', ())
        formfield.widget = cls(value=value, choices=choices)
class PlayWidget(Widget):
    """A widget that features a Play button if provided with a path towards
    a wav file.

    """
    num_wavs = 0
    """number of fields with wavs rendered using PlayWidget so far"""

    def __init__(self, attrs=None):
        super(PlayWidget, self).__init__(attrs)
        self.hidinput = HiddenInput()

    def render(self, name, value, attrs=None):
        # Merge attributes from self.attr and attrs argument.
        final_attrs = self.build_attrs(attrs)

        # Render the link plus the wav player if applicable.
        content_html = self.render_content(name, value, attrs)

        if 'add_link' in final_attrs and 'db_field' in final_attrs:
            db_field = final_attrs['db_field']
            model = db_field.model
            link_html = get_object_link(model, {db_field.attname: value})[1]
        else:
            link_html = mark_safe(u'')

        # Render the form element that retains information about the
        # corresponding model field and its value.
        hidden_html = self.hidinput.render(name, value, attrs)
        return (hidden_html + content_html + link_html)

    def render_content(self, name, value, attrs=None):
        if (not hasattr(value, 'startswith')
                or not value.startswith(CONVERSATION_DIR)):
            return mark_safe('N/A')
        wav_rest = value[len(CONVERSATION_DIR):]
        context = {'wav_fname': wav_rest,
                   'script_id': unicode(PlayWidget.num_wavs),
                   'MEDIA_URL': MEDIA_URL,
                   'APP_PATH' : APP_PATH}
        PlayWidget.num_wavs += 1
        player_html = render_to_string("trs/wav_player.html",
                                       dictionary=context)
        return player_html
 def __init__(self, attrs=None):
     super(PlayWidget, self).__init__(attrs)
     self.hidinput = HiddenInput()
Ejemplo n.º 7
0
    def render(self, name, value, attrs=None):
        """
        Code for rendering this widget
        
        name - Name of form field
        value - CroppedImageFile being cropped
        """

        if value is None:
            return ""

        if not isinstance(value, CroppedImageFile):
            raise ValueError("ImageCropCoordinatesInput requires a CroppedImageFile value")

        # Only display cropping control if the file has been saved to disk
        if isinstance(value.file, InMemoryUploadedFile) or not hasattr(value, "url"):
            return ""

        output = []

        final_attrs = self.build_attrs(attrs)
        id_ = final_attrs.get("id", None)
        aspect_ratio = final_attrs.pop("aspect_ratio", 0.0)

        if not self.is_hidden:
            # Only render image cropping util if image_url has been set
            t = Template(
                """
            <script language="Javascript">
                jQuery(window).load(function(){
                    jQuery('#{{id}}-imagecrop-popup-link').click(function(){
                        var popup = window.open('{% url imagecrop.views.imagecrop_popup %}','','height=700,width=650');
                        popup.jCropArgs = {
                            {%spaceless%}
                            {% if boxWidth %}
                            boxWidth:{{boxWidth}},
                            {%endif%}
                            {% if boxHeight %}
                            boxHeight:{{boxHeight}},
                            {%endif %}
                            {%endspaceless%}
                            aspectRatio: {{aspectRatio}},
                            trueSize:[{{trueWidth}},{{trueHeight}}]
                        };
                        
                        popup.image_orig_thumbnail='{{imageurl}}';
                        popup.image_thumb_height={{orig_thumbnail_image.height}};
                        popup.image_thumb_width={{orig_thumbnail_image.width}};
                        popup.image_selected_coords=[{{coords.x1}},{{coords.y1}},{{coords.x2}},{{coords.y2}}];
                        popup.crop_update_callback=updateCoords;
                    
                    });
                
                    function updateCoords(coords){
                        jQuery('#{{id}}_x1').val(coords.x);
                        jQuery('#{{id}}_y1').val(coords.y);
                        jQuery('#{{id}}_x2').val(coords.x2);
                        jQuery('#{{id}}_y2').val(coords.y2);
                        
                        //Updating CSS
                        jQuery('#{{id}}-imagecrop-popup-block').css('background-color','yellow');
                        jQuery('#{{id}}-imagecrop-popup-message').html('Save Required')
                    };
                    
                });  
                
            </script>
            <div id="{{id}}-imagecrop-popup-block" style="display:block; text-align:center;">
            <a id="{{id}}-imagecrop-popup-link" href="javascript:return True;">
            <img src="{{cropped_thumbnail_url}}" id='{{id}}' />
            <div id="{{id}}-imagecrop-popup-message" style="display:block">
            Click to adjust cropping
            </div>
            </a>
            </div>
            """
            )

            orig_thumbnail_path = os.path.join(settings.MEDIA_ROOT, value.orig_thumbnail_filename)

            if not os.path.exists(orig_thumbnail_path):
                value.generate_orig_thumbnail_file()

            orig_thumbnail_image = ImageFile(open(orig_thumbnail_path))

            cropped_thumbnail_path = os.path.join(settings.MEDIA_ROOT, value.cropped_thumbnail_filename)
            if not os.path.exists(cropped_thumbnail_path):
                value.generate_cropped_thumbnail_file()

            c = Context(
                {
                    "id": id_,
                    "aspectRatio": aspect_ratio,
                    "imageurl": settings.MEDIA_URL + value.orig_thumbnail_filename,
                    "cropped_thumbnail_url": settings.MEDIA_URL + value.cropped_thumbnail_filename,
                    "coords": value.crop_coords,
                    "boxWidth": self.crop_image_width,
                    "boxHeight": self.crop_image_height,
                    "trueWidth": value.width,
                    "trueHeight": value.height,
                    "orig_thumbnail_image": orig_thumbnail_image,
                }
            )
            output.append(t.render(c))

        for param in ImageCropCoordinatesInput.COORD_PARAMS:
            widget = HiddenInput()

            if id_:
                final_attrs = dict(final_attrs, id="%s_%s" % (id_, param))
            coord = getattr(value.crop_coords, param) if value.crop_coords else None
            output.append(widget.render("%s_%s" % (name, param), coord, final_attrs))

        return mark_safe(u"".join(output))
Ejemplo n.º 8
0
    def render(self, name, value, attrs=None):
        try:
            year_val, month_val, day_val = value.year, value.month, value.day
        except AttributeError:
            year_val = month_val = day_val = None
            if isinstance(value, basestring):
                match = RE_DATE.match(value)
                if match:
                    year_val, month_val, day_val = [int(v) for v in match.groups()]
        output = []

        start_date = now - relativedelta(months=self.month_range)
        end_date = now + relativedelta(months=self.month_range)

        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = 'id_%s' % name

        day_choices = [(i, i) for i in range(1, 32)]
        if not (self.required and value):
            day_choices.insert(0, self.none_value)
        local_attrs = self.build_attrs(id=self.day_field % id_)
        s = Select(choices=day_choices)
        select_html = s.render(self.day_field % name, day_val, local_attrs)
        block_html = """<span class='%(class)s day'>%(select_html)s</span>"""
        output.append(block_html % {
            'class': local_attrs['class'],
            'select_html': select_html,
            })

        yearmonth_choices = []
        ddate = start_date
        while ddate < end_date:
            yearmonth_choices.append(('%s-%s' % (ddate.year, ddate.month), '%s %s' % (unicode(capfirst(MONTHS[ddate.month])), ddate.year)))
            ddate = ddate + relativedelta(months=1)
        if not (self.required and value):
            yearmonth_choices.append(self.none_value)

        local_attrs['id'] = self.yearmonth_field % id_
        s = Select(choices=yearmonth_choices)
        select_html = s.render(self.yearmonth_field % name, '%s-%s' % (year_val, month_val), local_attrs)
        block_html = """<span class='%(class)s yearmonth'>%(select_html)s</span>"""
        output.append(block_html % {
            'class': local_attrs['class'],
            'select_html': select_html,
            })

        local_attrs['id'] = self.datepicker_field % id_
        i = HiddenInput()
        input_html = i.render(self.datepicker_field % name, None, local_attrs)
        output.append(input_html)

        other_html = render_to_string('adlibre/contrib/widgets/selectdatewidget.html', {
            'id_datepicker_field': self.datepicker_field % id_,
            'id_day_field': self.day_field % id_,
            'id_yearmonth_field': self.yearmonth_field % id_,
            'class': local_attrs['class'],
            'month_range': self.month_range,
            })
        output.append(other_html)

        return mark_safe(u'\n'.join(output))
Ejemplo n.º 9
0
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        """
        self.user = kwargs.pop('user', None) # Should never be None
        if self.user is None:
            raise PermissionDenied # Idk if this is the right error I should raise
        """
        self.event = kwargs.pop('instance')
        super(UpdateEventForm, self).__init__(*args, **kwargs)
        """
        self.fields['title'].widget.attrs.update({"value" : self.event.title})
        self.fields['start'].widget = DateTimeInput(attrs={"value" : self.event.start})
        self.fields['end'].widget = DateTimeInput(attrs={"value" : self.event.end})
        self.fields['address_id'].widget.attrs={"value" : self.event.address_id}
        self.fields['image'].widget.attrs.update({"value" : self.event.image})
        self.fields['ticket_deadline'].widget.attrs.update({"value" : self.event.ticket_deadline})
        self.fields['see_remaining'].widget.attrs.update({"value" : self.event.see_remaining})
        self.fields['premium_flag'].widget.attrs.update({"value" : self.event.premium_flag})
        """
        self.intern = self.event.tickets.filter(ticket_type=Ticket.INTERN)
        self.extern = self.event.tickets.filter(ticket_type=Ticket.EXTERN)
        self.staff = self.event.tickets.filter(ticket_type=Ticket.STAFF)
        self.nb_intern = self.intern.count()
        self.nb_extern = self.extern.count()
        self.nb_staff = self.staff.count()
        self.intern_purchase = self.event.participants.filter(
            ticket_id__ticket_type=Ticket.INTERN)
        self.intern_purchase_nb = self.intern_purchase.count()
        self.extern_purchase = self.event.participants.filter(
            ticket_id__ticket_type=Ticket.EXTERN)
        self.extern_purchase_nb = self.extern_purchase.count()
        self.staff_purchase = self.event.participants.filter(
            ticket_id__ticket_type=Ticket.STAFF)
        self.staff_purchase_nb = self.staff_purchase.count()
        self.fields['title'].required = False
        self.fields['start'].required = False
        self.fields['end'].required = False
        self.fields['image'].required = False
        self.fields['ticket_deadline'].required = False
        self.fields['see_remaining'].required = False
        self.fields['premium_flag'].initial = self.event.premium_flag
        self.fields['start'].widget = DateTimeInput(
            attrs={"placeholder": "2017-12-25 14:30:59"})
        self.fields['end'].widget = DateTimeInput(
            attrs={"placeholder": "2017-12-25 14:30:59"})
        self.fields['address_id'].label = _("Address")
        self.fields['address_id'].initial = Address.objects.get_or_create(
            raw="")[0]
        self.fields['address_id'].required = False
        intern_field = self.fields['intern_number']
        intern_field.widget.attrs['min'] = self.intern_purchase_nb
        intern_field.initial = self.nb_intern
        intern_field.help_text = _('total : %d | bought : %d') % \
                (self.nb_intern, self.intern_purchase_nb)
        extern_field = self.fields['extern_number']
        extern_field.widget.attrs['min'] = self.extern_purchase_nb
        extern_field.initial = self.nb_extern
        extern_field.help_text = _('total : %d | bought : %d') % \
                (self.nb_extern, self.extern_purchase_nb)
        staff_field = self.fields['staff_number']
        staff_field.widget.attrs['min'] = self.staff_purchase_nb
        staff_field.initial = self.nb_staff
        staff_field.help_text = _('total : %d | selected staff: %d') % \
                (self.nb_staff, self.staff_purchase_nb)
        staffs_field = self.fields['staffs']
        # should maybe make a staff model with an event and a member
        # would select members from asso where not already staff
        wanted = self.event.assos_id.members.all().values_list('user',
                                                               flat=True)
        unwanted = self.event.participants.filter(
            ticket_id__ticket_type=Ticket.STAFF).values_list('user', flat=True)
        staffs_field.queryset = User.objects.filter(id__in=wanted).exclude(
            id__in=unwanted)

        try:
            price = self.event.prices.get(ticket_type=Ticket.INTERN).price
            intern_price = self.fields['intern_price']
            intern_price.initial = price
            intern_price.help_text = _('current price in shop is %d') % price
        except Price.DoesNotExist:
            pass
        try:
            price = self.event.prices.get(ticket_type=Ticket.EXTERN).price
            extern_price = self.fields['extern_price']
            extern_price.initial = price
            extern_price.help_text = _('current price in shop is %d') % price
        except Price.DoesNotExist:
            pass

        if not self.user.has_perm('event.choose_premium'):
            self.fields['premium_flag'].widget = HiddenInput()