Django ModelFormSet对象在发布时更改类型

时间:2019-02-05 20:57:23

标签: python django django-forms formset

我正在将页面从使用手动呈现的发布/获取功能转换为使用基于类的视图的页面。我正在尝试使用Django的所有内置功能。但是我遇到一个令人困惑的错误,即在发布表单时,ModelFormSet对象不是正确的类型。

我有这个表格:

class AssignmentDatesForm(forms.ModelForm): 

class Meta:
    model = AssignmentDates
    fields = [
    'assignment_name',
    'start_date',
    'due_date',
    'end_date',
    ]

    widgets = { 'start_date' : forms.DateInput(format = '%m/%d/%Y', attrs ={ 'class' : 'datepicker'}),
                'due_date' : forms.DateInput(format = '%m/%d/%Y', attrs ={ 'class' : 'datepicker' }),
                'end_date' : forms.DateInput(format = '%m/%d/%Y', attrs ={ 'class' : 'datepicker' }),}

def clean(self):
    logging.warning("Clean function")
    logging.warning("start_date: " + str(start_date))
    logging.warning("due_date: " + str(due_date))
    logging.warning("end_date: " + str(end_date))
    # Actual validation logic here

并使用modelformset_factory创建ModelFormSet:

AssignmentDatesFormSet = forms.modelformset_factory(
model = AssignmentDates,
form = AssignmentDatesForm,
extra = 0,
) 

这里是视图,为简洁起见,已缩短:

class EditDueDates(CurrentUserMixin, ModelFormSetView):
model = AssignmentDates
page_title = 'Edit Due Dates'

success_message = "Dates updated successfully!"
add_button_title = "Add Button Title"
form = AssignmentDatesForm
formset = AssignmentDatesFormSet
template_name = "edit_due_dates.html"
sidebar_group = ['scaffold', 'edit_due_dates']

columns = [
    ('Assignment Name', 'assignment_name'),
    ('Start Date', 'start_date'),
    ('Due Date', 'due_date'),
    ('End Date', 'end_date'),
    ]

fields = [
'assignment_name',
'start_date',
'due_date',
'end_date',
]

show_context_menu = False

def get_context_data(self, **kwargs):
    context = super(EditDueDates, self).get_context_data(**kwargs)

    # Date retrieval/ DB storage logic here

    form = AssignmentDatesFormSet(queryset = AssignmentDates.objects.filter(created_by = creds.get_OUNetID()))
    logging.warning("get_context_data form type: " + str(type(form)))
    context['form'] = form
    return context

def formset_valid(self, formset):
    logging.warning("formset_valid form type: " + str(type(formset)))
    cleaned_data = formset.clean()
    if formset.is_valid():
        formset.save()            
    return super(EditDueDates, self).formset_valid(formset)

ModelFormSet在模板中显示良好,上面的日志消息将打印出如下表格类型:

 <class 'scaffold.forms.AssignmentDatesFormSet'>

但是我的clean函数从未执行过。当它执行视图中的formset_valid函数并打印出formset类型时,我得到以下信息:

<class 'django.forms.formsets.AssignmentDatesFormFormSet'>

因此它永远不会执行我的clean函数,因为类型不正确。再次执行formset.clean()只是执行此奇怪类型的clean函数。

我不知道为什么从模板中发布它时,它是一种不同的类型。如果有人有任何想法,请告诉我!谢谢!

-将

0 个答案:

没有答案