将init方法放在InLineFormSet上

时间:2017-01-31 15:21:44

标签: python django init

我使用InLineFormSet显示与特定时间表相关的所有记录。用户可以在页面上添加许多新表单,我使用ajax和html在底部附加一个空的existing_form和新ID。但是保存这个问题是因为新添加的表单还没有分配timesheet_id,它们不会保存为existing_forms的一部分。

我正在尝试将init方法放在一起,在创建表单时分配它,希望能解决这个问题。 (?)

1)我必须保存记录才能成为existing_formset的一部分吗?

2)我已经从TimeForm中排除了timesheet_id ....这意味着我假设form.timesheet_id = var将无法工作......我将不得不使用obj.timesheet_id ......但是我可以在表格的初始化?很困惑。

3)为新添加的表单使用新的formset更容易并使用modelformset_factory .....

查看:

class CustomInlineFormSet(BaseInlineFormSet):
    def clean(self):
        super(CustomInlineFormSet, self).clean()
        timesheet = TimeSheet.objects.get(pk=timesheet_id)
        for form in self.forms:
            form.empty_permitted = True
    def __init__(self, request, *args, **kwargs):
        super(CustomInlineFormSet, self).__init__(*args,**kwargs)
        # the following won't work because it's excluded from the form?
        # self.fields['timesheet_id'] = forms....... oh no
        timesheet_fromview = request.session.get('timesheet')
        print timesheet_fromview
        for form in self.forms:
            obj = form.save(commit=False)
            obj.timesheet_id = timesheet_fromview

        try:
            del request.session['timesheet']
            print "session deleted"
        except KeyError:
            pass
            print "Key error raised"



def timesheet(request, timesheet_id):
    timesheet = TimeSheet.objects.get(pk=timesheet_id)

    TimeInlineFormSet = inlineformset_factory(TimeSheet, Time, exclude=('timesheet_id',), extra=0, formset=CustomInlineFormSet)

    if request.method == 'POST':
        # instance is not yet timesheet.... no foreign key in new fields so doesn't do anything
        existing_formset = TimeInlineFormSet(request.POST, request.FILES, instance=timesheet)

        for thetime in existing_formset.forms:
            # obj = thetime.save(commit=False)
            # obj.timesheet_id = timesheet
            # obj.save()
            # print obj
            if thetime.is_valid():
                print "existing time is valid"
                thetime.save()
            else:
                "existing time is not valid"

        context = {
            "timesheet": timesheet,
            "existing_formset": existing_formset,
        }    
        return render(request, 'tande/timesheet.html', context)
    else:
        print "method is not post"
        existing_formset = TimeInlineFormSet(instance=timesheet)
        new_timeformset = NewTimeFormSet()
        request.session['timesheet'] = timesheet
        context = {
            "timesheet": timesheet,
            "existing_formset": existing_formset,
        }    
        return render(request, 'tande/timesheet.html', context)

1 个答案:

答案 0 :(得分:0)

我通过在视图中使用两个单独的formset来实现这一点,一个内联现有记录,一个modelformset用于新添加。然后我分别用一个字段保存两个字段,当记录是新添加时为True,当它在现有formset中时为False:

class Time(models.Model):
    project_id = models.ForeignKey(Project, null=True)
    date_worked = models.DateField(null=True, blank=True)
    hours = models.CharField(max_length=1)
    description = models.CharField(max_length=150)
    timesheet_id = models.ForeignKey(TimeSheet, null=True)
    add_row = models.CharField(max_length=10, default=True, editable=False)
    def __unicode__ (self):
        return self.description

视图分别保存两个表单集:

def timesheet(request, timesheet_id):
    timesheet = TimeSheet.objects.get(pk=timesheet_id)

    TimeInlineFormSet = inlineformset_factory(TimeSheet, Time, exclude=('timesheet_id',), extra=0, formset=CustomInlineFormSet)
    NewTimeFormSet = modelformset_factory(Time, form=TimeForm, formset=RequiredFormSet)

    if request.method == 'POST':
        existing_formset = TimeInlineFormSet(request.POST, request.FILES, instance=timesheet)
        newtime_formset = NewTimeFormSet(request.POST, request.FILES)

        for orange in newtime_formset:
            obj = orange.save(commit=False)
            if obj.add_row == "True":
                obj.timesheet_id = timesheet
                obj.add_row = "False"
                obj.save()

        for thetime in existing_formset.forms:
            if thetime.is_valid():
                thetime.save()

        existing_formset = TimeInlineFormSet(instance=timesheet)
        newtime_formset = NewTimeFormSet()
        context = {
            "timesheet": timesheet,
            "existing_formset": existing_formset,
            "newtime_formset": newtime_formset,
        }    
        return render(request, 'tande/timesheet.html', context)