Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

268
Views
Django form: formatting data from an instance before render

Using Django 1.11, one of my models is an array stored within a django-jsonfield field.

class MyModel(models.Model)
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    core = JSONField(blank=True, null=True, default=None)

I am using a ModelForm in a couple of views to create and edit new instances. Within the ModelForm I'm borrowing the django.contrib.postgres.forms.SimpleArrayField to parse the input into the field.

Adding a new model is fine, but in the edit version, the array gets pre-populated with what looks like the __str__ representation (eg an array of 1,2,3 becomes ['1','2','3'].

I'm getting around this by parsing the array into initial= for each form but I'd rather do this in one place (DRY) rather than having to repeat it inside each view and form instance.

Are there any hooks or methods (perhaps a custom widget?) that means I can do this just once in the form or somewhere else?

Snippet of the current view with hacky approach using initial=:

def edit_mymodel(id):
    current_instance = MyModel.objects.get(pk=id)
    if request.method == "GET":
        form = MyModelForm(instance=current_instance,
                           initial={"core": ",".join(current_instance.core)}
                           )
        return render(request, 'network_manager/edit.html',
                      {'form': form}
                      )
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can override __init__

class MyModelForm(ModelForm)
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.initial['core'] = ",".join(self.instance.core)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!