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

286
Visualizações
How to prefill django form Dynamically

I am trying to display a form in django and pre-filling it dynamically. I want the user of my sample news gathering site to modify an entry.

I have my Manual Input form class

#forms.py
class ManualInputForm(forms.Form):
    source = forms.CharField(label="Source:", widget = forms.TextInput(attrs={'size': 97}))
    topic  = forms.CharField(label="Topic:", widget = forms.TextInput(attrs={'size': 97}))
    news   = forms.CharField(widget = forms.Textarea(attrs={"rows":5, "cols":100}))
    link   = forms.CharField(label="Link (optional):", required = False, widget = forms.TextInput(attrs={'size': 97}))

In the HTML I am going manually because I would like to pre-fill all fields with data coming in from the related function in views.py.

#html file
<form method="post" class="form-group">
    {% csrf_token %}
    <div class="input-group mb-3">
        <div class="container">
            {% for field in form  %}
                <div class="fieldWrapper">
                    {{ field.errors }}
                    {{ field.label_tag }}
                    <br>
                    {{ field }}
                </div>
            {% endfor %}
        </div>

        <div class="input-group">
            <p> </p>
            <button type="submit" class="btn btn-success" name="Submit">Save</button>
        </div>
    </div>
</form>

How do I do it? It's driving me crazy o.O I would like to keep using django's forms because of its integrated error manager (not all fields are required but some are and I'd like for django to keep managing it).

Thank your for your suggestions!

EDIT: as requested I'll post the views.py related function:

#views.py
def editnews(response, id):
    form = ManualInputForm(response.POST or None)

    #tableToView is a dataframe retrieved by querying an external DB
    #data cannot be stored in django's buit in because of reasons ;-)

    #checking the dataframe is correct and it is:
    #IT IS MADE OF A SINGLE LINE
    
    print(tableToView)

    #THIS IS PROBABLY NOT THE WAY TO DO IT
    form.source = tableToView.loc[0, 'Source']
    form.topic  = tableToView.loc[0, 'Topic']
    form.news   = tableToView.loc[0, 'News']
    form.link   = tableToView.loc[0, 'Link']

    return render(response, 'manual/editnews.html', {"form":form})

In the image the text should be pre-filled.

enter image description here

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Try something like that:

def editnews(response, id):
    data = {k.lower(): v for k, v in tableToView.loc[0].to_dict().items()}
    form = ManualInputForm(response.POST or None, initial=data)
    return render(response, 'manual/editnews.html', {'form': form})
about 4 years ago · Juan Pablo Isaza Relatório

0

when you are declaring or rendering form in view and sending it to template. use initial argument and pass dictionary in it with key as name of field and value as the text which you want prefilled.

like this context['form'] = NameofForm(initial={'Source':'mysite', 'Topic':'mytopic'}) return context

Update

> def test_view(request, pk):   
>     template_name = 'form.html'
>     form = MyForm(initial={"test":"initialize with this value"})
>         if request.method == 'POST':
>             form = MyForm(request.POST)
>             if form.is_valid():
>                 form.save()
>                 return HttpResponseRedirect(reverse('list-view'))
> 
>     return render(request, template_name, {'form': form})
about 4 years ago · Juan Pablo Isaza Relatório

0

Try this:


#views.py
def editnews(response, id):
    data = {}
    data["source"] = tableToView.loc[0, 'Source']
    data["topic"] = tableToView.loc[0, 'Topic']
    data["news"] = tableToView.loc[0, 'News']
    data["link"] = tableToView.loc[0, 'Link']

    form = ManualInputForm(response.POST or None, initial=data)

    return render(response, 'manual/editnews.html', {"form":form})
about 4 years ago · Juan Pablo Isaza 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