Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass initial value to a modelform in django

How can I pass an initial value for a field to a model form. I have something like the following code

class ScreeningForm(forms.ModelForm):
    class Meta:
        model = Screening

    def __init__(self, *args, **kwargs):
        super(ScreeningForm, self).__init__(*args, **kwargs)
        self.fields['blood_screen_type'] =  CommaSeparatedCharField(
            label=self.fields['blood_screen_type'].label,
            initial=self.fields['blood_screen_type'].initial,
            required=False,
            widget=CommaSeparatedSelectMultiple(choices=BLOOD_SCREEN_TYPE_CHOICES)
        )

class ScreeningAdmin(admin.ModelAdmin):
    #form = ScreeningForm
    form = ScreeningForm(initial={'log_user':get_current_user()})

Now I want to pass an initial value for a field of the Person class. How can I do that?

like image 383
rajan sthapit Avatar asked Sep 22 '11 10:09

rajan sthapit


People also ask

What is initial in Django form?

initial is used to change the value of the field in the input tag when rendering this Field in an unbound Form. initial accepts as input a string which is new value of field. The default initial for a Field is empty.

What is Is_valid () in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What is instance in form Django?

It also means that when Django receives the form back from the browser, it will validate the length of the data. A Form instance has an is_valid() method, which runs validation routines for all its fields. When this method is called, if all fields contain valid data, it will: return True.


1 Answers

You can pass initial value to a ModelForm like this:

form = PersonForm(initial={'fieldname': value})

For example, if you wanted to set initial age to 24 and name to "John Doe":

form = PersonForm(initial={'age': 24, 'name': 'John Doe'})

Update

I think this addresses your actual question:

def my_form_factory(user_object):
    class PersonForm(forms.ModelForm):
        # however you define your form field, you can pass the initial here
        log_user = models.ChoiceField(choices=SOME_CHOICES, initial=user_object)
        ...
    return PersonForm

class PersonAdmin(admin.ModelAdmin):
    form = my_form_factory(get_current_user())
like image 113
Derek Kwok Avatar answered Oct 15 '22 13:10

Derek Kwok