I am creating a web-app w/ Flask + Flask-WTF that has CRM-like features as a project. My current database (MongoDB) structure is I have:
- Users who can login,
- People who are assigned to users, and
- Records who are assigned to people.
People have various fields to be filled out (Name, Phone Number, Email, etc).
I want Users to be able to create custom fields for people. I am trying to plan out how to implement this from a database design perspective. My initial thoughts are to:
- For each field created, add a new field without a value for each People assigned to the user.
- Use a for-loop to dynamically create the form class by looping through each field-value in my database and excluding non-required ones.
- Use a for-loop to dynamically output the web form by looping through each field-value in my database and excluding non-required ones.
Another idea I have is:
- For each field created, add the custom field, with a parentRecord equal to the User ID to a new MongoDB collection.
- Use a for-loop to create the form class & web form dynamically, but I wouldn’t need to exclude non-required ones as the only fields in the collection would be the custom ones, and wouldn’t include any special data points that don’t get displayed.
So my questions are:
- Will my ideas above work?
- Which one is better?
- Is there a better way?
Advertisement
Answer
I decided to create a customfields MongoDB collection that has a parentRecord as the User.
I faced a few challenges:
I had to dynamically create a form via flask WTF. I ended up using
wtforms_dynamic_fields
to accomplish this. I then used a for-loop to dynamically generate each form in Jinja. I simply queried the customfields DB where the parentRecord matched the logged in User, and then created custom fields based upon the values saved in customfields.The second issue I faced was getting the data from the submitted form and then building a MongoDB-friendly list to insert a new record with when creating new record. This was accomplished by using
request.form.items()
and iterating through them and usinglist.update()
to add all of my required fields to a list.