views:

90

answers:

0

I have a Django model that looks like this:

DEFAULT_PROFILE_INFO = [
    {"name":"About Me", "body":"Super programmer", "public":True},
    {"name":"Research", "body":"Various topics", "public":False}
]

class Profile(models.Model):
    user = models.OneToOneField(User, unique=True)
    info = JSONField(blank=True, default=DEFAULT_PROFILE_INFO)

And its associated form class:

class ProfileForm(forms.ModelForm):
    info = forms.CharField(widget=forms.Textarea())

    class Meta:
        model = Profile
        exclude = ('user',)

The goal of the above is to give users rudimentary profile editing, capable of adding more info blocks to their own profiles without predetermination. Displaying the information entered works flawlessly for the end viewer, but I'm running into problems creating the form controls for this type of data. The code above renders the full JSON string into a text box. I would like to create forms that abstract the JSON structure away from the user, presenting them with a TextInput, Textarea, and Checkbox for each block.

The concept I have in mind is creating a Form to cover one info block, and grouping them into a FormSet within the ProfileForm as a field. Clearly FormSets were not designed with such a usage in mind, but on first glance this doesn't seem impossible.

What would be the best way (or ideas of ways) to implement this?

Note: Although another way to do this would be to remove the info blocks into their own relational table, we are trying to avoid this. I'm hoping to stick with the JSON implementation, unless someone can present an excellent reason or two why we should not go that route.