ria
ria

Reputation: 7508

how can I make a Django model form with a field name in the form different from the model field name?

I have a model and a form like this:

class Content(models.Model):
    title = models.CharField(_("title"), max_length=16)
    category = models.ForeignKey(Category, verbose_name = _('category'))

class ContentForm(forms.ModelForm):
    class Meta:
        model=Content
        fields = ('title', 'category', )

I would like to have the name of the field in the form to be f_category (of course the name of the field in the model is to stay category). Is it possible to do that, without having to construct the whole form manually (which is difficult because the field is a ForeignKey and has to be a select field with a list of options)?


To clarify: by name I mean the name as in the HTML form code: <input type="select" name="f_category" />

Upvotes: 4

Views: 3096

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599610

Your comment reveals what you actually need to do - this is why you should always describe your actual problem, not your proposed solution. Naturally, there is a proper way to deal with two identical forms on the same page in Django - use the prefix parameter when instantiating the field.

form1 = MyForm(prefix='form1')
form2 = MyForm(prefix='form2')

Now when you output form1 and form2, all the fields will automatically get the relevant prefix, so they are properly separated.

Upvotes: 6

Zach Kelling
Zach Kelling

Reputation: 53819

I'm not sure what you mean by "the name of the field in the form". Do you mean the label? Or the id? Or something else? Configuring the label is pretty easy:

class ContentForm(forms.ModelForm):
    category = forms.ModelChoice(queryset=Category.objects.all(), label='f_category')
    class Meta:
        model=Content
        fields = ('title', 'category', )

Upvotes: 1

Related Questions