Home > Enterprise >  How to keep html form data after submission using django?
How to keep html form data after submission using django?

Time:07-02

I created a form in html that returns data to Django each time it is submitted. However, when the page is reloaded after submission, the data entered in the form is lost. In order to solve this problem, I took inspiration from the documentation and this blog and then I modified my views.py file:

def search(request):
    if request.method == 'POST':
        search = request.POST['search']
        form = MyForm(request.POST)
        max_pages_to_scrap = 15
        final_result = []
        for page_num in range(1, max_pages_to_scrap 1):
            url = "https://www.ask.com/web?q="   search   "&qo=pagination&page="   str(page_num)
            res = requests.get(url)
            soup = bs(res.text, 'lxml')
            result_listings = soup.find_all('div', {'class': 'PartialSearchResults-item'})

            for result in result_listings:
                result_title = result.find(class_='PartialSearchResults-item-title').text
                result_url = result.find('a').get('href')
                result_desc = result.find(class_='PartialSearchResults-item-abstract').text
           
                final_result.append((result_title, result_url, result_desc))

        context = {'final_result': final_result}
        form = MyForm()

        return render(request, 'index.html', context,{'form':form})

I wrote the following code in my models.py file:

from django import forms
from django.db import models 

# Create your models here.

class MyForm(forms.Form):
    search = forms.CharField(max_length=500)

here is the content of my index.html file:

<form method="POST" action="search">
                        {% csrf_token %}
                        <input  type="search" name="search" placeholder="Search here..." value="{{form.search.value}}" autofocus x-webkit-speech/>
                       
                </form>

Despite my modifications, the form data is not kept after submission.

CodePudding user response:

It cannot be saved, because you are passing brand new form to context:

...
form = MyForm()

return render(request, 'index.html', context,{'form':form})

Just move form = MyForm() to something like elif request.method == 'GET'::

if request.method == 'POST':
    ...
    form = MyForm(request.POST)
    ...
    for page_num in range(1, max_pages_to_scrap 1):
        ...

elif request.method == 'GET':
    form = MyForm()

context = {'final_result': final_result, 'form': form}

return render(request, 'index.html', context)

PS Keep form with your context, it's way clearer.

  • Related