Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom fields to a django model (without changes in source code)

A customer wants to add custom fields to a django model we provide.

He wants to do this on his own, without programming.

These things should be addable:

  • boolean (yes/no) fields. Optional "unset"
  • single choice fields
  • multiple choice fields
  • single line text fields
  • textarea fields
  • date

Example:

The customer wants to add a field he calls "was successful". And the field > should have these choices: yes/no/unset. Defaulting to unset.

Things would be easy if I could do it by creating or extending a model. But in this case no source code changes are allowed :-(

How to solve this?

Update

Querying for instances with given values needs to be supported. Example: Show all instances where "was successful" is True.

like image 215
guettli Avatar asked Feb 10 '16 08:02

guettli


3 Answers

You can create a table that follows the EAV principle (Entity Attribute Value). Basically this is a denormalised table with following columns:
[ID (and/or slug), float_value, integer_value, string_value] (Add more columns to this table)

Now say you've a existing table called "Member". When customer adds a dynamic field via your UI, you add the entries here and use "ID" to look them up for a given member.

like image 129
Siddharth Srivastava Avatar answered Nov 03 '22 16:11

Siddharth Srivastava


I use Django Dynamic Forms. Out of the box, it lets users create their own forms through the admin. You might want to extend it to build a more user-friendly UI, but this should get you pretty far. It supports

  • boolean
  • choices (select)
  • multiple choices (multiple select)
  • date
  • datetime
  • time
  • email
  • integer
  • single line text
  • multi line text
like image 2
Felix Böhme Avatar answered Nov 03 '22 15:11

Felix Böhme


Well, when I had such problem, I used to create a custom field model, with a name field and a type field, usually a choice field with choices for the possible field types. You can also add a is_active field to filter the active and inactive CustomFields.

Than, when I create the for, I search this objects to know which fields I must have in that form.

To store the data, I'd have another model, called CustomFieldAnswer, or somethink like this. This model should have a ForeignKey to the main model that should have this data, and the custom field.

Doing so, You can have any kinds of fields for yout model dinamically and wothout you client needing to code anything.

You could use metaprogramming to create acutual fields in a form based on the query in the CustomFields. Or, you could just put the fields in the template and change the type of the input for each CustomField.

Hope that helps!

like image 2
Julio Cesar Eiras Melanda Avatar answered Nov 03 '22 14:11

Julio Cesar Eiras Melanda