Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" />

like image 290
ria Avatar asked Sep 03 '25 13:09

ria


2 Answers

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.

like image 172
Daniel Roseman Avatar answered Sep 05 '25 02:09

Daniel Roseman


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', )
like image 30
zeekay Avatar answered Sep 05 '25 01:09

zeekay