简体   繁体   English

如何制作 Django model 表单,其字段名称与 model 字段名称不同?

[英]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:我有一个 model 和这样的表格:

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 ).我希望表单中的字段名称为f_category (当然 model 中的字段名称是留在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)?是否可以这样做,而不必手动构建整个表单(这很困难,因为该字段是 ForeignKey 并且必须是带有选项列表的 select 字段)?


To clarify: by name I mean the name as in the HTML form code: <input type="select" name="f_category" />澄清一下:我所说的名称是指 HTML 表单代码中的名称: <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.当然,在 Django 的同一页面上,有一种正确的方法可以处理两个相同的 forms - 在实例化字段时使用prefix参数。

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.现在当你 output form1 和 form2 时,所有的字段都会自动得到相关的前缀,所以它们被适当地分开了。

I'm not sure what you mean by "the name of the field in the form".我不确定“表单中字段的名称”是什么意思。 Do you mean the label?你的意思是label? Or the id?还是身份证? Or something else?或者是其他东西? Configuring the label is pretty easy:配置 label 非常简单:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM