How to give initial value in modelform

前端 未结 2 2118
梦如初夏
梦如初夏 2021-02-12 21:44

How do I assign initial values to fields inside a ModelForm? eg:

class Form1(forms.Form):
    title=forms.CharField(initial=\"hello\")

What wil

相关标签:
2条回答
  • 2021-02-12 22:08

    Model Form defaults are taken from the model itself. For example:

    class SomeModel(models.Model):
        title  = models.CharField(max_length=45, default="hello")
    

    You don't need to make any changes to your ModelForm:

    class RequestForm(forms.ModelForm):
    
        class Meta:
            model = SomeModel
    
    0 讨论(0)
  • 2021-02-12 22:21

    Normally you would pass the model object you are editing as instance keyword arg to the form: Form2(instance = somemodelobject), but I don't know if it works on GAE. You can always pass initial dictionary to your form's constructor, like

    Form2(initial = {"title": "blahblah"})
    
    0 讨论(0)
提交回复
热议问题