views:

29

answers:

1

I have a ModelForm as follows:

class ArticleForm(forms.ModelForm):
    title = forms.CharField(max_length=200)
    body = forms.CharField(widget=forms.Textarea)
    new_status = forms.CharField(label="Status", max_length=1,  widget=forms.Select(choices=APPS_ARTICLE_STATUS))
    tags = forms.CharField(label="Generic Tags", max_length=200, widget=forms.TextInput(attrs={'size':'40'}))

    class Meta:
        model = Article
        fields = ['title', 'body']

Of this title, body and new status load directly from the Article model. I want to populate the tags field manually. How do I go about doing this?

Thanks in advance.

A: 

You can set the initial property via the __init___ method. Also, you don't need to specify every field label/widget again, if the verbose_name is set on the model, and you like the default widgets.

class ArticleForm(forms.ModelForm):

    tags = forms.CharField(label="Generic Tags", max_length=200, widget=forms.TextInput(attrs={'size':'40'}))

    class Meta:
        model = Article
        fields = ['title', 'body', 'new_status']

    def __init__(self, *args, **kwargs):
        super(ArticleForm, self).__init__(*args, **kwargs)
        self.fields["tags"].initial = "Some initial value"

I'm assuming your initial value will be dynamic somehow. If it's really static, you can pass initial in as a parameter when on the CharField().

Chase Seibert
Thanks, that worked perfectly! What's your best resource for documentation on the subject?
Nick