Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give initial value in modelform

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

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

What will be the equivalent for this using modelForm whose basic syntax is something like:

class Form2(djangoforms.ModelForm):
    class Meta:
        model=SomeModel
        fields=('title',)

What I am trying to do is generate a CRUD. Since I am doing it in an appengine project I can't use generic views. Appengine has provided us djangoforms.ModelForm which works just like the django's ModelForm but uses appengine's datastore.

I need the above functionality to do the "edit" part.

like image 421
Dhushyanth Avatar asked Jun 28 '09 08:06

Dhushyanth


2 Answers

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"})
like image 163
Pyetras Avatar answered Nov 02 '22 12:11

Pyetras


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
like image 43
Paul J Avatar answered Nov 02 '22 13:11

Paul J