A
A
Alexey Semyonov2018-11-07 18:13:24
Django
Alexey Semyonov, 2018-11-07 18:13:24

How to set default form value in django?

Model:

class MyModel(models.Model):
    enterprise = models.ForeignKey(Enterprise, verbose_name=_(u'Предприятие'), unique=True)
    retry = models.PositiveIntegerField(verbose_name=_(u'Количество попыток'), default=0)
    delay = models.PositiveIntegerField(verbose_name=_(u'Задержка между попытками, с'), default=1)

The form:
class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['retry'].required = False
        #не работает
        #self.fields['retry'].initial = 1

    #тоже не работает
    #delay = forms.IntegerField(label=_(u"title"), initial=1, required=False)

    class Meta:
        model = MyModel
        fields = ('enterprise', 'retry', 'delay')

Here is my form, it is necessary that when the form is opened, the "retry" and "delay" fields should already have numbers. I honestly don't understand how else to do it. For me, the strangest thing is required works, but initial does not work

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-11-07
@iGyry

Either define default values ​​in the model

class MyModel(models.Model):
   retry = models.PositiveSmallIntegerField(default=1)
   ...

or pass the corresponding model instance to the form constructor
or pass the initial field values ​​to the form constructor
All this is described in detail in the documentation .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question