Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

276
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda