Render the searchform in a view

In this lesson, we are going to render our searchform in a view, and then have that view rendered in a template.

NOTE: In this lesson, we will get the code that we used in the Using Static Files in Django lesson and build upon it.

Step 1: Make a view for a form

In this step, we are going to define a view called forms. See the following lines:

from .forms import SearchForm

def forms(request):
    form = SearchForm()
    return render(request,'first_app/forms.html', {'form': form})

Let’s breakdown what we did here.

  • We first imported our SearchForm from the .forms file.

  • Since SearchForm is a class, we have to instantiate it and put it in form.

  • first_app/forms.html is the template in which we will render our form.

Let’s create the first_app/forms.html template next.

Step 2: Make a template to render the form

In this step, we create a file forms.html inside of the first_app directory, and then we put the following lines:

<form method="GET" action="https://google.com ">
    {{form}}
    <input type="submit" value="Search">
</form>

In the snippet given above, we are simply rendering our form inside the <form> tag, and adding a submit button to take us to google.com.

And that’s it. This code will render our form.

Step 3: Make a URL for that form

In first_app/urls.py file we will add the following line:

path('forms/',views.forms,name="form"),

Step 4: Run the code

In this step, we just need to run the code to see it work.

NOTE: We have configured the environment below to take you to the /forms/ page when RUN is pressed.

Also, feel free to add more fields in the forms.py file to see how they work.

Get hands-on with 1200+ tech skills courses.