Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7625303
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T05:10:27+00:00 2026-05-31T05:10:27+00:00

I have a model with a field for a json object. This object is

  • 0

I have a model with a field for a json object. This object is used on the site to control some css variables, among other things.

Right now in the admin, I have a text field where a user can save a json object. I’d like to show a form with all the attributes that, upon saving, will generate a json object.

Basically, the user sees, and the data is stored, like this:

{
    "name":"hookedonwinter",
    "user-id":123,
    "basics":{
        "height":150,
        "weight":150
        }
}

And I’d rather have the user see this:

Name: <input field>
User Id: <input field>
Height: <input field>
Weight: <input field>

and the data still be stored in json.

Any guidance would be appreciated. Links to docs that explain this, doubly appreciated.

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T05:10:28+00:00Added an answer on May 31, 2026 at 5:10 am

    Idea

    Basically what you need to do is render your JSON into fields.

    1. Create field for your model that stores JSON data.
    2. Create form field
    3. Create widget that:
      1. Renders fields as multiple inputs
      2. Takes data from POST/GET and transforms it back into JSON

    You can also skip steps 1, 2 by overriding widget for TextField.

    Documentation links

    • Widgets: https://docs.djangoproject.com/en/1.3/ref/forms/widgets/
    • Django code for reference how to create widgets: https://code.djangoproject.com/browser/django/trunk/django/forms/widgets.py

    Proof of concept

    I tried coding this solution and here is solution that worked for me without some edge cases.

    fields.py

    import json
    
    from django.db import models
    from django import forms
    from django import utils
    from django.utils.translation import ugettext_lazy as _
    
    
    class JSONEditableField(models.Field):
        description = _("JSON")
    
        def formfield(self, **kwargs):
            defaults = {'form_class': JSONEditableFormField}
            defaults.update(kwargs)
            return super(JSONEditableField, self).formfield(**defaults)
    
    class JSONEditableWidget(forms.Widget):
        def as_field(self, name, key, value):
            """ Render key, value as field """
            attrs = self.build_attrs(name="%s__%s" % (name, key))
            attrs['value'] = utils.encoding.force_unicode(value)
            return u'%s: <input%s />' % (key, forms.util.flatatt(attrs))
    
        def to_fields(self, name, json_obj):
            """Get list of rendered fields for json object"""
            inputs = []
            for key, value in json_obj.items():
                if type(value) in (str, unicode, int):
                    inputs.append(self.as_field(name, key, value))
                elif type(value) in (dict,):
                    inputs.extend(self.to_fields("%s__%s" % (name, key), value))
    
            return inputs
    
        def value_from_datadict(self, data, files, name):
            """
            Take values from POST or GET and convert back to JSON..
            Basically what this does is it takes all data variables
            that starts with fieldname__ and converts
            fieldname__key__key = value into json[key][key] = value
            TODO: cleaner syntax?
            TODO: integer values don't need to be stored as string
            """
            json_obj = {}
    
            separator = "__"
    
            for key, value in data.items():
                if key.startswith(name+separator):
                    dict_key = key[len(name+separator):].split(separator)
    
                    prev_dict = json_obj
                    for k in dict_key[:-1]:
                        if prev_dict.has_key(k):
                            prev_dict = prev_dict[k]
                        else:
                            prev_dict[k] = {}
                            prev_dict = prev_dict[k]
    
                    prev_dict[dict_key[-1:][0]] = value
    
            return json.dumps(prev_dict)
    
    
        def render(self, name, value, attrs=None):
            # TODO: handle empty value (render text field?)
    
            if value is None or value == '':
                value = '{}'
    
            json_obj = json.loads(value)
            inputs = self.to_fields(name, json_obj)
    
            # render json as well
            inputs.append(value)
    
            return utils.safestring.mark_safe(u"<br />".join(inputs))
    
    class JSONEditableFormField(forms.Field):
        widget = JSONEditableWidget
    

    models.py

    from django.db import models
    from .fields import JSONEditableField
    
    class Foo(models.Model):
        text = models.TextField()
        json = JSONEditableField()
    

    Hope this helps and here is how it looks:
    Result

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have model Article it has field title with some text that may contain
Let's say I have this model named Product with a field named brand .
Say I have a model object 'Person' defined, which has a field called 'Name'.
Specifically, I have a model that has a field like this pub_date = models.DateField(date
I have a problem when I update an object. This is the model: class
I have model Foo which has field bar. The bar field should be unique,
I'd like to have access to one my model field verbose_name. I can get
I have a model Question with a field called userid , before one ask
I have a model Model with a m2m field : user = .. fk
I have an ActiveRecord model with a field called name (in the database) and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.