为 Formset Django 循环初始数据

Looping Initial Data for Formset Django

我想每 1 小时为 TimeField 的字段在 formset 中设置初始数据 24。

所以想要的输出:00:00, 01:00, 02:00, 03:00,..., 22:00, 23:00 like下图:

我尝试了以下代码但没有结果:

profiles = UserProfile.objects.filter(username=username)


initial_formset = [{
        'user': item.name,
        'time': datetime.datetime.now(). + datetime.timedelta(hours=1),
    }
for item in profiles]

MyFormset = formset_factory(MyForm, extra=24)
formset = MyFormset(initial=initial_formset)

我们将不胜感激。

*请求更新:

Forms.py:

class TestBaseFormSet(BaseFormSet):
    def get_form_kwargs(self, index):
        kwargs = super().get_form_kwargs(index)
        kwargs['custom_kwarg'] = index
        return kwargs

class MyForm(forms.Form):
    user = forms.CharField(required=False, label="", widget=forms.TextInput(attrs={'class': "form-control"}))
    date = forms.DateField(required=False, label="", initial=get_today, input_formats=settings.DATE_INPUT_FORMATS, widget=DatePickerInput(format="%d/%m/%Y", attrs={'class': "form-control"}))
    time = forms.TimeField(required=False, label="", input_formats=settings.TIME_INPUT_FORMATS, widget=TimePickerInput(format="%H:%M", attrs={'class': "form-control"}))

    def __init__(self, *args, **kwargs):
        custom_kwarg = kwargs.pop('custom_kwarg')
        super().__init__(*args, **kwargs)
        self.fields['time'].initial = datetime.datetime.now() + datetime.timedelta(hours=custom_kwarg)

Views.py:

def create(request, username):
    profiles = get_object_or_404(UserProfile, username=username)

    MyFormSet = formset_factory(MyForm, extra=24, formset=TestBaseFormSet)

    if request.method == 'POST':
        formset = MyFormSet(request.POST or None)

        if formset.is_valid():
            for item in formset:
                profile = MyModel()
                profile.user = profiles
                profile.date = item.cleaned_data['date']
                profile.time = item.cleaned_data['time']
                profile.save()

            return redirect('home')
        else:
            messages.warning(request, formset.errors)
    else:
        formset = MyFormset()

    context = {
        'profiles': profiles,
        'formset': formset,
    }

    return render(request, 'index.html', context)

为您的表单集定义一个 Baseformset class。从 Django.forms

导入 BaseFomrmSet
class TestBaseFormSet(BaseFormSet):
def get_form_kwargs(self, index):
    kwargs = super().get_form_kwargs(index)
    kwargs['custom_kwarg'] = index
    return kwargs

MyFormset = formset_factory(MyForm, extra=24,formset=TestBaseFormSet)

class MyForm(forms.Form):
time_field = forms.DateTimeField()

def __init__(self,*args,**kwargs):
    custom_kwarg = kwargs.pop('custom_kwarg')
    super().__init__(*args, **kwargs)
    self.fields['time_field'].initial = datetime.datetime.now() + datetime.timedelta(hours=custom_kwarg)