gamer
gamer

Reputation: 5863

django set multiple initial value in formsets

I have a form:

class TimingForm(forms.ModelForm):
class Meta:
    model = Timing
    fields = ('day','mng_start', 'mng_end', 'eve_start', 'eve_end')

I am making formset out of this form .

TimingFormSet = modelformset_factory(Timing, form=TimingForm, extra=7)

Here in the 'day' field of form I want the days of the week i.e. sun, mon... sat. Also I want to set it as that user cannot edit this field. I was about to use readonly field but came to know that djano's readonly field is not appriciated.

How can I make this possible. Setting initial value and making it uneditable.

Upvotes: 0

Views: 1615

Answers (1)

Hasan Ramezani
Hasan Ramezani

Reputation: 5194

change your form like this:

class TimingForm(forms.ModelForm):
    class Meta:
        model = Timing

    def __init__(self, *args, **kwargs):
        super(TimingForm, self).__init__(*args, **kwargs)
        self.fields['day'].widget.attrs['readonly'] = True

    fields = ('day','mng_start', 'mng_end', 'eve_start', 'eve_end')

for initialize forms with day of week you can use this:

day_of_week = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
formset = TimingFormSet()
for form, day in zip(formsets, day_of_week):
    form.initial['day'] = day

Now formset forms initialized with day of week in day field.

Upvotes: 3

Related Questions