Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

275
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda