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

281
Views
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 answers
Answer question

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 Report

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 Report

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