开发者

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


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.


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', )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜