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

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

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 Denunciar

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 Denunciar

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 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