Home > OS >  How to prefill django form Dynamically
How to prefill django form Dynamically

Time:12-29

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" >
    {% csrf_token %}
    <div >
        <div >
            {% for field in form  %}
                <div >
                    {{ field.errors }}
                    {{ field.label_tag }}
                    <br>
                    {{ field }}
                </div>
            {% endfor %}
        </div>

        <div >
            <p> </p>
            <button type="submit"  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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

You could do it with jQuery if you're using one. You'll need to set the attribute of id to the form field.

jQuery code example:

$('#topic').val("Prefilled text goes here");

  • Related