使用自定义小部件创建+更新

时间:2016-08-05 09:57:58

标签: django django-models django-forms django-views

我创建了一个自定义小部件,其中包含“SelecTimeWidget”& “SelectDateWidget” 当我创建一个新事件但我把它变成一个(UpdateView)

时,它工作正常

我收到错误

global name 'to_current_timezone' is not defined

我不知道如何解决这个问题,以便在创建和编辑活动时使用小部件。

class EventUpdateView(UpdateView):
    form_class = CreateEvent
    model = Event



class EventCreateView(CreateView):
    form_class = CreateEvent
    model = Event

    def form_valid(self, form):
        Event = form.save(commit=False)
        Event.created_by = self.request.user
        Event.save()
        return HttpResponseRedirect('/calendar/')



class CreateEvent(forms.ModelForm):
    class Meta:
        model = Event
        fields = ['title', 'start', 'end', 'description', 'category']
        widgets = {

            'start': SelectDateTimeWidget(date_format= '%m/%m/%Y'),
            'end': SelectDateTimeWidget(date_format= '%d/%m/%Y')
        }

Widget,显然SelectTimeWidget也是一个自定义的,但错误导致我在下面的代码中的“value = to_current_timezone(value)”这一行

class SelectDateTimeWidget(forms.MultiWidget):
    supports_microseconds = False

    def __init__(self, attrs=None, date_format=None, time_format=None):
        widgets = (SelectDateWidget(empty_label=( "Year", "Month", "Day")),
                   SelectTimeWidget(use_seconds=False))
        super(SelectDateTimeWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            value = to_current_timezone(value)
            return [value.date(), value.time().replace(microsecond=0)]
        return [None, None]

    def subwidgets(self, name, value, attrs=None):
        if self.is_localized:
            for widget in self.widgets:
                widget.is_localized = self.is_localized
        # value is a list of values, each corresponding to a widget
        # in self.widgets.
        if not isinstance(value, list):
            value = self.decompress(value)
        output = []
        final_attrs = self.build_attrs(attrs)
        id_ = final_attrs.get('id')
        for i, widget in enumerate(self.widgets):
            try:
                widget_value = value[i]
            except IndexError:
                widget_value = None
            if id_:
                final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
            output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
        return output

有人知道解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

"from django.forms.util import to_current_timezone"

我没有意识到To_current_timezone是一个导入,一旦我发现它工作了:)

爱好在经过一段时间的担忧后回答我自己的问题