Django:允许用户向模型添加字段 [英] Django: allow user to add fields to model

查看:101
本文介绍了Django:允许用户向模型添加字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是从Django开始,并想为应用程序创建模型。

I am just starting with Django and want to create a model for an application.

我发现
具有Djangos功能-自动定义验证和html小部件根据模型中定义的字段类型和
的形式选择表单类型-为模型
中的字段定义一个选择集非常有用,我想充分利用它。另外,我想充分利用管理界面。

I find Djangos feature to - automatically define validations and html widget types for forms according to the field type defined in the model and - define a choice set for the field right in the model very usefull and I want to make best use of it. Also, I want to make best use of the admin interface.

但是,如果我想允许应用程序的用户向模型添加字段,该怎么办?例如,考虑一本简单的地址簿。我希望用户能够在管理设置中为其所有联系人定义其他属性,即添加传真号码字段,以便可以将传真号码添加到所有联系人。

However, what if I want to allow the user of the application to add fields to the model? For example, consider a simple adress book. I want the user to be able to define additional atributes for all of his contacts in the admin settings, i.e. add a fax number field, so that a fax number can be added to all contacts.

从关系数据库的角度来看,我将有一个带有属性的表(PK:atr_ID,atr_name,atr_type)以及属性和带有外键的联系人之间的N:N关系来自属性和联系人-即它将在数据库中生成3个表。

from a relational DB perspective, I would have a table with atributes (PK: atr_ID, atr_name, atr_type) and an N:N relation between atributes and contacts with foreign keys from atributes and contacts - i.e. it would result in 3 tables in the DB. right?

,但是那样我不能直接在Django模型中定义字段类型。现在,这里的最佳做法是什么?我如何利用Django的功能并允许用户通过管理界面添加附加/自定义字段?

but that way I cannot define the field types directly in the Django model. Now what is best practice here? How can I make use of Djangos functionality AND allow the user to add aditional/custom fields via the admin interface?

谢谢! :)

最佳
Teconomix

Best Teconomix

推荐答案

I'我曾经在 django-payslip 中首次看到的这种方法允许扩展字段。这提供了用于向模型添加字段的结构,您可以从中允许用户通过标准的查看过程添加/编辑(无需管理员进行黑客攻击)。这足以让您入门,并查看django-payslip的源代码(请参阅视图),还提供了视图Mixins和表单,作为如何向用户呈现的示例。

I've used this approach, first seen in django-payslip, to allow for extendable fields. This provides a structure for adding fields to models, from which you can allow users to add/edit through standard view procedures (no admin hacking necessary). This should be enough to get you started, and taking a look at django-payslip's source code (see the views) also provides view Mixins and forms as an example of how to render to users.

class YourModel(models.Model):
    extra_fields = models.ManyToManyField(
        'your_app.ExtraField',
         verbose_name=_('Extra fields'),
         blank=True, null=True,
    )


class ExtraFieldType(models.Model):
    """
    Model to create custom information holders.
    :name: Name of the attribute.
    :description: Description of the attribute.
    :model: Can be set in order to allow the use of only one model.
    :fixed_values: Can transform related exta fields into choices.
    """
    name = models.CharField(
        max_length=100,
        verbose_name=_('Name'),
    )

    description = models.CharField(
        max_length=100,
        blank=True, null=True,
        verbose_name=_('Description'),
    )

    model = models.CharField(
        max_length=10,
        choices=(
            ('YourModel', 'YourModel'),
            ('AnotherModel', 'AnotherModel'), # which models do you want to add extra fields to?
        ),
        verbose_name=_('Model'),
        blank=True, null=True,
    )

    fixed_values = models.BooleanField(
        default=False,
        verbose_name=_('Fixed values'),
    )

    class Meta:
        ordering = ['name', ]

    def __unicode__(self):
        return '{0}'.format(self.name)



class ExtraField(models.Model):
    """
    Model to create custom fields.
    :field_type: Connection to the field type.
    :value: Current value of this extra field.
    """
    field_type = models.ForeignKey(
        'your_app.ExtraFieldType',
        verbose_name=_('Field type'),
        related_name='extra_fields',
        help_text=_('Only field types with fixed values can be chosen to add'
                    ' global values.'),
    )

    value = models.CharField(
        max_length=200,
        verbose_name=_('Value'),
    )

    class Meta:
        ordering = ['field_type__name', ]

    def __unicode__(self):
        return '{0} ({1}) - {2}'.format(
            self.field_type, self.field_type.get_model_display() or 'general',
            self.value)

这篇关于Django:允许用户向模型添加字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆